原题链接:
https://vjudge.net/problem/CodeForces-767C
AC代码:
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int INF = 0x3fffffff;
void __init__()
{
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
}
int n;
int sum;
int tem[1000050];
int pre[1000050];
int val[1000050];
stack<int> ans;
vector<int> son[1000050];
void dfs(int pos)
{
val[pos] = tem[pos];
int num_son = son[pos].size();
if (num_son > 0)
{
for (int i = 0; i < num_son; i++)
{
dfs(son[pos][i]);
val[pos] += val[son[pos][i]];
}
}
if (val[pos] * 3 == sum && pos != son[0][0] && ans.size() < 2)
{
ans.push(pos);
val[pos] = 0;
}
}
int main()
{
__init__();
cin >> n;
sum = 0;
for (int i = 1; i <= n; i++)
{
cin >> pre[i] >> tem[i];
sum += tem[i];
son[pre[i]].push_back(i);
}
dfs(son[0][0]);
if (ans.size() == 2 && sum % 3 == 0)
{
cout << ans.top();
ans.pop();
cout << " " << ans.top() << endl;
ans.pop();
}
else
cout << "-1" << endl;
return 0;
}
日常补题,参考了马队的代码,真的强,清晰明了,非常适合我这种菜鸡参考Orz
这题答案不固定,用不同的容器存ans输出不同