fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define int long long
  4. const int MAXN = 1e6+5;
  5. int n, x, r, sum, cnt;
  6. vector<int> adj[MAXN], ans;
  7. int sub[MAXN], t[MAXN];
  8.  
  9. void dfs(int x, int p){
  10. sub[x] = t[x];
  11. for (int i : adj[x]){
  12. if (i != p){
  13. dfs(i,x);
  14. sub[x] += sub[i];
  15. }
  16. }
  17. if (sub[x] == sum/3 && x != r){
  18. ans.push_back(x);
  19. sub[x] = 0;
  20. // biar gak keitung dua kali
  21. }
  22. return;
  23. }
  24.  
  25.  
  26.  
  27. signed main(){
  28. ios::sync_with_stdio(0);
  29. cin.tie(0), cout.tie(0);
  30. cin >> n;
  31. for (int i =1; i <= n; i++){
  32. cin >> x >> t[i];
  33. sum += t[i];
  34. if( x== 0){
  35. //rootnya
  36. r = i;
  37. }
  38. else{
  39. adj[x].push_back(i);
  40. adj[i].push_back(x);
  41. }// sum += t[i];
  42.  
  43. }
  44. if (sum%3){
  45. cout << -1;
  46. return 0;
  47. }
  48. dfs(r,0);
  49. if ( ans.size() >= 2){
  50. cout << ans[0] << " " << ans[1] << endl;
  51. }
  52. else{
  53. cout << -1;
  54. }
  55.  
  56. }
Success #stdin #stdout 0.01s 30212KB
stdin
6
2 4
0 5
4 2
2 1
1 1
4 2
stdout
1 4