2300 years ago, Moriya Suwako was defeated by Yasaka Kanako in the Great Suwa War. As the goddess of mountains in Gensokyo, she was planning to make a comeback and regain faith among humans.
To achieve her great plan, she decides to build shrines in human villages. Of course, each village can bulid at most one shrine. If she builds a shrine in the i-th village, she can get Fifaith points.
Because of geological differences and the Quantum Entanglement theory, each village has one and only one entangled village Pi (it is a kind of one-way relationship). If Suwakobuilds shrines both in the i-th village and the Pi-th village, the faith she get from the i-th village will changes by Gi points (it can result to a negative value of faith points). If she only builds a shrine in the Pi-th village, but not in the i-th village, the faith she get will not changes.
Now, please help Suwako to find out the maximal faith points she can get.
There are multiple test cases. For each test case:
The first line contains an integer N (2 <= N <= 100000) indicates the number of villages in Gensokyo. Then followed by N lines, each line contains three integers Fi (0 <= Fi <= 100000) Gi (-100000 <= Gi <= 100000) Pi (1 <= Pi <= N and Pi will not point to the i-th village itself).
For each test case, output the maximal faith points that Suwako can get.
2 3 -1 2 2 -2 1 4 3 -2 2 4 -3 3 2 -1 1 5 -2 2
3 9
題意:在N個村莊選建聖地,如果在僅在PI建,不會損失滿意度,如果在PI的兒子節點
也建會損失G滿意度,問你選建時的最大滿意度
分析:咋一看跟普通的樹DP沒啥區別,設dp[i][1]:為在第i個點建的最大滿意度,dp[i][0]
不在第i個點建的最大滿意度,但是存在環,我們來分析這個環的特點,每個村莊僅有一個entangled village
也就是說連邊(有向)的時候每個點僅有一個入邊,如果存在環的話,只有可能從環上的點開始向環外的點
邊,而且不會存在雙環。所以我們就在環上選定一點,分選與不選做兩次樹形DP,取最大值即可。
對於不在環上的點直接拓撲排序排除掉即可。
#include#include #include #include #include #include #include #include #include