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. Input The first line
contains single integer n (3 ≤ n ≤ 106) — the number of lamps in the
garland. Then n lines follow. The i-th of them contain the information
about the i-th lamp: the number lamp ai, it is hanging on (and 0, if
is there is no such lamp), and its temperature ti ( - 100 ≤ ti ≤ 100).
The lamps are numbered from 1 to n. Output If there is no solution,
print -1. Otherwise print two integers — the indexes of the lamps
which mean Dima should cut the wires they are hanging on. If there are
multiple answers, print any of them.
先算出来总和,除以三就是每一块的和。树形dp算出子树和,需要找两个点满足要求。
但是要注意子树已经被切掉一块的情况,还有根节点是不能切下来的。
#include<cstdio>
#include<cstring>
int fa[1000010],val[1000010],size[1000010],vis[1000010],du[1000010],que[1000010],n;
int main()
{
int hd,tl,s=0,ans=-1,u;
scanf("%d",&n);
for (int i=1;i<=n;i++)
{
scanf("%d%d",&fa[i],&val[i]);
s+=val[i];
du[fa[i]]++;
}
if (s%3)
{
printf("-1\n");
return 0;
}
s/=3;
hd=1;
tl=0;
for (int i=1;i<=n;i++) if (!du[i]) que[++tl]=i;
while (hd<=tl)
{
u=que[hd++];
if (!fa[u]) break;
size[u]+=val[u];
if (size[u]-vis[u]*s==s)
{
if (ans==-1) ans=u;
else
{
printf("%d %d\n",ans,u);
return 0;
}
vis[u]=1;
}
if (vis[u]) vis[fa[u]]=1;
du[fa[u]]--;
size[fa[u]]+=size[u];
if (!du[fa[u]]) que[++tl]=fa[u];
}
printf("-1\n");
}