题目链接:http://codeforces.com/contest/767/problem/C

题解:类似于提着一串葡萄,用剪刀剪两条藤,葡萄分成了三串。问怎样剪才能使三串葡萄的质量相等。

首先要做的就是统计葡萄的总质量tot。之后就是找到两子串质量为(tot/3)的葡萄(如果除不尽,则必定找不到),那么剩下的就是dfs搜索了。

我一开始的做法是先建一棵记录子树质量和的树,然后再从上往下dfs,如果找到了,就把它剪掉。后来发现被剪掉的那一串可能就含有两串质量为(tot/3)的葡萄(这里质量 可为负数), 所以这种方法行不通。

那么正确的做法是先深入到最底层(叶子结点),然后再从下往上搜索,这个过程与建树的过程是一致的。所以可以将两个过程合并在一起。

代码如下:

 #include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<queue>
#include<vector>
#include<map>
#include<string>
#include<set>
#define LL long long
#define MAX(a,b) (a>b?a:b)
#define MIN(a,b) (a<b?a:b)
#define INF 0x7fffffff
#define LNF ((1LL<<62)-1)
#define maxn 200010 using namespace std; int n, tot = ,cnt = , sum[], vis[];
vector<int>child[];
int ans[]; int build(int rt)
{
vis[rt] = ;
int m = child[rt].size();
for(int i = ; i<m; i++)
{
if(!vis[child[rt][i]])
sum[rt] += build(child[rt][i]); if(cnt==)
return ;
} if(sum[rt]==tot)
{
ans[cnt++] = rt;
return ;
}
else return sum[rt];
} int main()
{
int rt,v;
scanf("%d",&n);
for(int i = ; i<=n; i++)
{
scanf("%d%d",&v,&sum[i]); if(v)
child[i].push_back(v);
child[v].push_back(i); tot += sum[i];
if(!v) rt = i, vis[rt] = ;
} if(tot%)
{
puts("-1");
return ;
} tot /= ;
int m = child[rt].size();
for(int i = ; i<m; i++)
{
build(child[rt][i]);
if(cnt==) break;
} if(cnt==)
printf("%d %d\n",ans[],ans[]);
else
puts("-1"); }

最新文章

  1. HTML5学习总结——canvas绘制象棋(canvas绘图)
  2. VS2013快捷键及技巧
  3. Web的结构组件
  4. 四种DLL:NON-MFC DLL, Regular DLL Statically/Dynamically Linked to MFC, MFC Extension DLL
  5. FPGA内部信号避免高阻态
  6. Openjudge 百练第4109题
  7. webservice和.net remoting浅谈
  8. javascript动态改变iframe的src
  9. iOS中怎样加入自己定义的字体
  10. Oracle在不同的语言环境结果to_date错误的问题
  11. 一起做orb-slam(2)
  12. 本人在CSDN上的技术博客访问量突破了10万次,特此截图留念
  13. 初入 vue
  14. js左右大小变化
  15. python———day03
  16. docker run命令运行以及参数详解
  17. 六.HashMap HashTable HashSet区别剖析总结
  18. invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun
  19. 关于“.bash_profile”和“.bashrc”区别的总结
  20. 714-Card Trick

热门文章

  1. Vijos——P1137 组合数
  2. Network | Public-key cryptography
  3. BZOJ1010玩具裝箱Toy
  4. The Process class relies on proc_open, which is not available on your PHP installation
  5. uibutton 使用settitle后如何修改其中文字对齐方式
  6. xamarin android 获取根证书代码
  7. Mybatis原理分析一 从JDBC到Mybaits
  8. hibernate session缓存
  9. cocos2dx3.0 对象池
  10. HDMI速率计算