Garland
题目地址:
基本思路:
首先我们知道只要整棵树的温度总和是确定的,
那么这个连通块的温度就也是确定的,
考虑树形,令表示以为根的子树的温度总和,
只要子树温度和等于,
那么我们就将这棵子树断开,消去这部分贡献,然后记录断点。
只要符合条件的断点数目大于等于,那么就是符合的。
参考代码:
#pragma GCC optimize(2) #pragma GCC optimize(3) #include <bits/stdc++.h> using namespace std; #define IO std::ios::sync_with_stdio(false); cin.tie(0) #define int long long #define ull unsigned long long #define SZ(x) ((int)(x).size()) #define all(x) (x).begin(), (x).end() #define rep(i, l, r) for (int i = l; i <= r; i++) #define per(i, l, r) for (int i = l; i >= r; i--) #define mset(s, _) memset(s, _, sizeof(s)) #define pb push_back #define pii pair <int, int> #define mp(a, b) make_pair(a, b) #define INF 0x3f3f3f3f inline int read() { int x = 0, neg = 1; char op = getchar(); while (!isdigit(op)) { if (op == '-') neg = -1; op = getchar(); } while (isdigit(op)) { x = 10 * x + op - '0'; op = getchar(); } return neg * x; } inline void print(int x) { if (x < 0) { putchar('-'); x = -x; } if (x >= 10) print(x / 10); putchar(x % 10 + '0'); } const int maxn = 1e6 + 10; struct Edge{ int to,next; }edge[maxn << 1]; int cnt = 0,head[maxn],w[maxn]; void add_edge(int u,int v){ edge[++cnt].next = head[u]; edge[cnt].to = v; head[u] = cnt; } int f[maxn],sum,tmp,tot,rt,ans[maxn]; void dfs(int u,int par) { f[u] = w[u]; for (int i = head[u]; i != -1; i = edge[i].next) { int to = edge[i].to; if (to == par) continue; dfs(to, u); f[u] += f[to]; } if (f[u] == tmp && u != rt) ans[++tot] = u,f[u] = 0; // 特别注意断点不能为根; } int n,x,t; signed main() { IO; cin >> n; cnt = 0,sum = 0; mset(head,-1); rep(i,1,n){ cin >> x >> w[i]; sum += w[i]; if(x == 0) rt = i; else add_edge(x,i),add_edge(i,x); } if(sum % 3 != 0) { cout << -1 << '\n'; return 0; } tmp = sum / 3,tot = 0; dfs(rt,0); if(tot >= 2){ cout << ans[2] << ' ' << ans[1] << '\n'; }else cout << -1 << '\n'; return 0; }