Submission
Status:
----------
Score: 0
User: Jokul
Problemset: สมดุลย์
Language: c
Time: 0.001 second
Submitted On: 2025-04-03 10:08:55
#include <stdio.h>
#include <stdlib.h>
typedef struct Rod {
int leftType; // 0 for rod, 1 for weight
int leftValue; // index of the left rod or weight value
int rightType; // 0 for rod, 1 for weight
int rightValue; // index of the right rod or weight value
int totalWeight; // total weight on this rod
int addedWeight; // weight to be added to balance this rod
} Rod;
Rod* rods;
int N;
void calculateWeights(int index) {
Rod* rod = &rods[index];
int leftWeight = 0, rightWeight = 0;
// Calculate left weight
if (rod->leftType == 0) {
calculateWeights(rod->leftValue - 1); // -1 for 0-based index
leftWeight = rods[rod->leftValue - 1].totalWeight;
} else {
leftWeight = rod->leftValue; // weight value
}
// Calculate right weight
if (rod->rightType == 0) {
calculateWeights(rod->rightValue - 1); // -1 for 0-based index
rightWeight = rods[rod->rightValue - 1].totalWeight;
} else {
rightWeight = rod->rightValue; // weight value
}
// Set total weight for this rod
rod->totalWeight = leftWeight + rightWeight;
// Calculate added weight needed to balance
if (leftWeight > rightWeight) {
rod->addedWeight = leftWeight - rightWeight;
} else {
rod->addedWeight = 0;
}
// Update the total weight with added weight
rod->totalWeight += rod->addedWeight;
}
int main() {
scanf("%d", &N);
rods = (Rod*)malloc(N * sizeof(Rod));
for (int i = 0; i < N; i++) {
scanf("%d %d %d %d", &rods[i].leftType, &rods[i].leftValue, &rods[i].rightType, &rods[i].rightValue);
rods[i].totalWeight = 0;
rods[i].addedWeight = 0;
}
// Start calculating weights from the first rod
calculateWeights(0);
// Sum up the added weights
long long totalAddedWeight = 0;
for (int i = 0; i < N; i++) {
totalAddedWeight += rods[i].addedWeight;
}
printf("%lld\n", totalAddedWeight);
free(rods);
return 0;
}