Streaming is miserable, but it won't be dropped because it has not been submitted during the competition (or even dropped) rating. The second question is a tree-like DP, but I am thinking about the first question, and it is almost dead.
I am also drunk looking at God's code... A variety of macros, It is really good to write Will Die series. seeing the DFS they use in tree DP, I suddenly felt that my life was full of powerlessness...
I generally like to use BFS for tree DP. there are many disadvantages, such as difficulties in debugging and space explosion. there are also advantages: Fast writing, short code, fast running, and simple judgment. however, there are conditions for doing so, and today's streaming is a good question.
Let's talk about lcastat today.
As a regression without writing Tarjan LCA, this question is of high quality. at least you don't need to perform LCA (doubling on a tree is similar ). some gods are so violent that I can only represent orz.
Let's think about how to calculate his (also called the LCA score) for each vertex?
How can we make the two vertices LCA a given vertex I?
Obviously, these two points must be I or in different Subtrees of I, so we gradually have a new idea.
Note that there is a simple way to calculate sum (x) {sum (y) {x * y}, that is, sum (x) {x} * sum (y) {y}
Find the totalweight of each subtree. When a node accesses a new subnode, the contribution of this point to the score is totw [I] * (noww [d] + W [d]) * 2
Totw [I] is the totalweight OF THE accessed child node, and noww [d] is the total weight of the Child tree that has been added to this parent node (excluding the newly accessed one, W [d] is the weight of this parent node.
Why multiply by 2? Because the order of this question is considered, that is, a = 3, B = 5, and a = 5, B = 3 are counted twice.
Every time all the child nodes of a node are accessed, the node is relaxed.
Check the code and go to all mod.
# Include <cstdio> # include <cstring> long fat [200000], W [200000], F [200000], sub [200000], totw [200000], n, p, I, sum; Long Q [200000], Qh, QT; int main (INT argc, char const * argv []) {scanf ("% LLD ", & N, W + 1); for (I = 2; I <= N; ++ I) {scanf ("% LLD", fat + I, W + I); ++ sub [Fat [I];} for (I = 1; I <= N; ++ I) {f [I] = 0; if (! Sub [I]) {q [QT ++] = I; totw [I] = 0; F [I] = 0 ;}} while (Qh! = QT) {I = Q [QH ++]; F [I] + = (W [I] * W [I]) * (W [I] + totw [I] * 2); totw [I] + = W [I]; sum = sum + F [I]; f [Fat [I] + = (totw [I] * totw [Fat [I]) * W [Fat [I] * 2; totw [Fat [I] + = totw [I]; -- sub [Fat [I]; If (! Sub [Fat [I]) Q [QT ++] = fat [I];} printf ("% LLD \ n", sum); Return 0 ;} // non-AC code, just for a clear DEMO code
Code style and tree-like DP