CF734E:Anton and Tree(缩点 & 直径)
来源:互联网 发布:上帝在掷骰子吗 知乎 编辑:程序博客网 时间:2024/06/05 12:07
题意:一棵树有两种颜色,每次操作可以将一个节点及其所在的联通块变色,问使整棵树变成同一种色要几次操作。
思路:缩点,求树的直径d,(d+1)/2就是答案,即从最长链的中间开始变色。
# include <bits/stdc++.h># define pb push_backusing namespace std;const int maxn = 2e5+30;vector<int>v[maxn], s[maxn];int ans=0, a[maxn], cnt=0, vis[maxn], h[maxn], fa[maxn];void dfs(int cur, int tag){ vis[cur] = 1; fa[cur] = tag; for(auto to : v[cur]) { if(vis[to] || a[to] != a[cur] ) continue; vis[to] = 1; dfs(to, tag); }}void dfs2(int cur, int pre){ int mx=0, mmx=0; for(auto to : s[cur]) { if(to == pre) continue; dfs2(to, cur); mx = max(mx, h[to]+1); if(mx > mmx) swap(mx, mmx);//维护两个最深的儿子。 } h[cur] = mmx; ans = max(ans, mx+mmx);}int main(){ int n; scanf("%d",&n); for(int i=1; i<=n; ++i) scanf("%d",&a[i]); for(int i=1; i<n; ++i) { int a, b; scanf("%d%d",&a,&b); v[a].pb(b), v[b].pb(a); } for(int i=1; i<=n; ++i) if(!vis[i]) dfs(i, ++cnt); for(int i=1; i<=n; ++i) for(auto j : v[i]) if(a[j] != a[i]) s[fa[i]].pb(fa[j]); dfs2(1, 0); printf("%d\n",(ans+1)/2); return 0;}
阅读全文
0 0
- CF734E:Anton and Tree(缩点 & 直径)
- E. Anton and Tree(缩点+树直径模板)
- Codeforces 734E Anton and Tree (dfs缩点+树的直径)
- Codeforces 734E. Anton and Tree By Assassin 缩点+树的最大直径
- Codeforces 734E Anton and Tree【并查集缩点||DFS缩点+树的直径】
- Codeforces-734E Anton and Tree(树的直径)
- 【CodeForces734E】【缩点】Anton and Tree 题解
- [Codeforces734E]Anton and Tree 树的直径
- 【codeforces 734E】Anton and Tree【缩点+DP】
- 思路题,树的直径(Anton and Tree,cf 734E)
- codeforces 734 E. Anton and Tree (黑红树,缩点+dfs)
- Codeforces Round #379 (Div. 2)E. Anton and Tree(dfs缩点,想法题)
- Codeforces Round #379 (Div. 2) E. Anton and Tree —— 缩点 + 树上最长路
- Anton and Tree CodeForces
- Codeforces 734E Anton and Tree【并查集缩点+树的直径】好题~
- CodeForces 734 E.Anton and Tree(dfs)
- CodeForces 734E - Anton and Tree
- 【27.91%】【codeforces 734E】Anton and Tree
- 今日计划
- 数据结构8:希尔排序专题
- Java 生成随机日期,时间
- Codeforces-417D总结&题解
- servletServletConfigAndServletContext
- CF734E:Anton and Tree(缩点 & 直径)
- LeetCode500. Keyboard Row
- 轻松将电气数据集成到您的机械设计
- CodeForces
- a.length==0、a==null、a == ""、a.equals("") 的区别
- vue中的video
- 【引用】web性能测试基本知识
- leetcode-26&80 Remove Duplicates from Sorted Array I & II
- hdu 6058 链表 枚举