1 条题解
-
-1
树链剖分+树上差分
#include<bits/stdc++.h> using namespace std; const int N = 5e4+10; int n, k; vector<int> g[N]; int fa[N], top[N], son[N], dep[N], sz[N], cnt[N], ans; void dfs1(int x, int father){ fa[x] = father, dep[x] = dep[father] + 1,sz[x] = 1; for (auto k : g[x]){ if(k == father) continue; dfs1(k,x); sz[x] += sz[k]; if(sz[son[x]] < sz[k]) son[x] = k; } } void dfs2(int x, int t){ top[x] = t; int s = son[x]; if(!s) return; dfs2(s,t); for(auto k : g[x]){ if(k == fa[x] || k == s) continue; dfs2(k,k); } } int lca(int u, int v){ while(top[u] != top[v]){ if(dep[top[u]] < dep[top[v]]) swap(u,v); u = fa[top[u]]; } return dep[u] < dep[v] ? u : v; } int dfs(int x, int father){ int tot = cnt[x]; for(auto k : g[x]){ if(k == father) continue; tot += dfs(k, x); } ans = max(ans, tot); return tot; } int main(){ cin >> n >> k; for (int i =1 ; i < n; i ++){ int a, b; cin >> a >> b; g[a].push_back(b); g[b].push_back(a); } dfs1(1,0); dfs2(1,1); while(k --){ int a, b; cin >> a >> b; int lc = lca(a,b); cnt[a] ++ , cnt[b] ++, cnt[lc] --, cnt[fa[lc]] --; } dfs(1,0); cout << ans; return 0; }
信息
- ID
- 2967
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 10
- 标签
- (无)
- 递交数
- 6
- 已通过
- 5
- 上传者