http://codeforces.com/contest/767/problem/C
Once at New Year Dima had a dream in which he was presented a fairy garland. A garland is a set of lamps, some pairs of which are connected by wires. Dima remembered that each two lamps in the garland were connected directly or indirectly via some wires. Furthermore, the number of wires was exactly one less than the number of lamps.
There was something unusual about the garland. Each lamp had its own brightness which depended on the temperature of the lamp. Temperatures could be positive, negative or zero. Dima has two friends, so he decided to share the garland with them. He wants to cut two different wires so that the garland breaks up into three parts. Each part of the garland should shine equally, i. e. the sums of lamps' temperatures should be equal in each of the parts. Of course, each of the parts should be non-empty, i. e. each part should contain at least one lamp.
Help Dima to find a suitable way to cut the garland, or determine that this is impossible.
While examining the garland, Dima lifted it up holding by one of the lamps. Thus, each of the lamps, except the one he is holding by, is now hanging on some wire. So, you should print two lamp ids as the answer which denote that Dima should cut the wires these lamps are hanging on. Of course, the lamp Dima is holding the garland by can't be included in the answer.
题意:找两条树枝剪断,使得将树划分为3个部分,每部分权值相等。
思路:整棵树的权和sum是一定的,那么3个部分各自的权值也是一定的。如果sum不是3的倍数一定无解,否则可能有解。
通过dfs,自根向叶子,如果某一棵子树权和是sum/3,那么就直接把它减下来,记录位置,告诉父亲子树权和为0。
这样一定是最优的,因为当前子树是sum/3,仅有可能在它的某个祖先结点使得从该子树上方到那个祖先节点的权和为0,才能够使得以那个祖先节点为根的子树权和是sum/3。
自己借着这样的考虑,在ac之后,认为:遇到sum/3剪掉子树,然后如果已经剪了两颗子树并且以当前结点为根的子树权和是0,那么说明在下面sum/3的结点再往上,权值正负抵消,减上面的这个而不是下面刚遇到sum/3也是没问题的,但是出了问题,经调试,发现是由于:设刚遇到为sum/3的结点为child,现在为0的是u,u未必是child的祖先!u不是child的祖先然后以u为根的子树权和为0,那么这样就错了。
还有一个要注意的:已经剪了两颗子树后,就不剪了,一开始自己的错误:假如sum/3是-6,已经剪了两颗-6的,然后递归返回在某个结点又-6了,不能剪这个,因为下面-6的剪掉,当成了0,这里的-6如果不剪下面的,实际是-12。事实上,已经剪了2棵子树,那么剩下的加起来一定是-6。
代码还是比较简单的,上面说的太繁琐了。
#include<bits/stdc++.h>
using namespace std;
#define maxn 1000000+1000
int n,fa,t[maxn],ans1,ans2,ans3,sum;
vector<int> child[maxn];
int dfs(int u)
{
int size=t[u];
for(int i=0;i<child[u].size();i++)size+=dfs(child[u][i]);
if(size==sum&&u!=child[0][0]&&!ans2)
{
if(!ans1)ans1=u;
else ans2=u;
size=0;
}
return size;
}
int main()
{
// freopen("input.in","r",stdin);
cin>>n;
for(int i=1;i<=n;i++)
{
scanf("%d%d",&fa,&t[i]);
child[fa].push_back(i);
sum+=t[i];
}
if(sum%3)
{
puts("-1");
exit(0);
}
sum/=3;
dfs(child[0][0]);
if(!ans2)puts("-1");
else printf("%d %d\n",ans1,ans2);
return 0;
}