This question has been completed for an afternoon. At last, I read other people's problem-solving reports. Let's talk about my understanding first. The general idea is to use the greedy idea to constantly merge the nodes with the largest weights with their parent nodes.
Process:
1. Set time [I] in the sequence to 1 at the beginning, and W [I] to C [I];
2. Find the largest W [I] and return its location;
3. Merge the C [] in this position with its parent node C [] (the merging process is C_ I/t_ I, C_ I = C [this node] + C [parent node], t_ I = time [this node] + time [parent node]) to obtain the new parent node W [] (W [parent node] = C_ I/t_ I ), if a node is connected to the POs, point it to the POs parent node;
4. Repeat steps 2 and 3 to know whether the merge is complete;
As for how to obtain the result: in the initial stage, ANS = sum (C [I]) is used. Each time a maximum weight value is found, ANS + = C [I] * time [parent node].
The Code is as follows:
# Include <iostream>
# Include <cstdio>
Using namespace STD;
Const int n= 1007;
Struct Node
{
Int t; // time []
Int P; // record the parent node
Int C; // C []
Double W; // W []
} Num [N];
Int N, R;
Int find () // find the maximum weight and return its location
{
Int Pos;
Double max = 0;
For (INT I = 1; I <= N; I ++)
If (Num [I]. W> MAX & I! = R) // POS cannot be the root node
{
Max = num [I]. W;
Pos = I;
}
Return Pos;
}
Int main ()
{
// Freopen ("data. In", "r", stdin );
Int I, j, A, B, POs, ANS, F;
While (scanf ("% d", & N, & R), N | r)
{
Ans = 0;
For (I = 1; I <= N; I ++)
{
Scanf ("% d", & num [I]. C );
Num [I]. W = num [I]. C; // W [I] is set to C [I] at the beginning;
Num [I]. T = 1; // time [I] is set to 1;
Ans + = num [I]. C; // initial ans = sum (C [I]);
}
For (I = 1; I <n; I ++)
{
Scanf ("% d", & A, & B );
Num [B]. P = A; // records the parent node and establishes a tree relationship.
}
I = N;
While (I> 1)
{
Pos = find (); // locate the maximum weight
Num [POS]. W = 0; // set it to 0 after finding it; otherwise, the next search will be affected.
F = num [POS]. P; // F is the parent node.
Ans + = num [POS]. C * num [f]. t; // Add the found C [POS] * time [f] To ans
For (j = 1; j <= N; j ++)
If (Num [J]. P = POS)
Num [J]. P = f; // If a node is connected to the POs, point it to the parent node of the POS.
Num [f]. C + = num [POS]. C; // C_ I = C [this node] + C [parent node]
Num [f]. t + = num [POS]. t; // t_ I = time [this node] + time [parent node]
Num [f]. W = (double) num [f]. c/num [f]. t; // weight of the merged F Node
I --;
}
Printf ("% d \ n", ANS );
}
Return 0;
}