Anton and Tree CodeForces
来源:互联网 发布:青牛软件待遇 编辑:程序博客网 时间:2024/06/05 20:58
题意:给出n个点,n-1条边构成一棵生成树,每个点都有黑白两种颜色,每次改变颜色都能使同颜色的相邻点改变颜色,求最小改变颜色的次数
思路:每次将一个联通块的颜色反转,比较容易想到每次反转后当前这个联通块的区域都会变的更大。
所以我们首先将这棵树进行缩点将相邻的相同颜色的点,缩为一点。缩点之后的树,每个节点都是原来的一个联通快。而将联通块的颜色反转等价于将这个缩点之后的树上的某个节点的全部相连的节点合并到当前节点。这样我们可以发现,我们每次在树上最长的链上做缩点操作能保证次数最少(每次都选中间的点),最少的次数为length/2。
所以题目就转变为求树的直径(最长路);
做法就是先从根1开始dfs找到最远点pos;然后dfs(pos);找到最远点;两点距离就是直径;
#include<bits/stdc++.h>using namespace std;#define maxn 233333int kind[maxn],vis[maxn];vector<int> mp1[maxn],mp2[maxn];void dfs(int a,int b)//压缩点{ if (vis[a]) return; vis[a]=true; if(kind[a]!=kind[b]) { mp2[a].push_back(b); mp2[b].push_back(a); b=a; } for(int i=0;i<mp1[a].size();i++) dfs(mp1[a][i],b);}int deep=0,pos;void len(int a,int l)//找最远点和长度{ if(vis[a]) return; vis[a]=1; if (l>deep) { deep=l; pos=a; } for(int i=0;i<mp2[a].size();i++) len(mp2[a][i],l+1);}int main(){ int n; scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%d",&kind[i]); for(int i=1;i<n;i++) { int a,b; scanf("%d%d",&a,&b); mp1[a].push_back(b); mp1[b].push_back(a); } memset(vis,0,sizeof(vis)); dfs(1,1); memset(vis,0,sizeof(vis)); len(1,0);// cout<<deep<<" "<<pos<<endl; memset(vis,0,sizeof(vis)); len(pos,0);// cout<<deep<<" "<<pos<<endl; printf("%d\n",(deep+1)/2);}
阅读全文
0 0
- Anton and Tree CodeForces
- CodeForces 734E - Anton and Tree
- 【27.91%】【codeforces 734E】Anton and Tree
- 【codeforces 734E】Anton and Tree【缩点+DP】
- CodeForces 734 E.Anton and Tree(dfs)
- Codeforces-734E Anton and Tree(树的直径)
- Codeforces Anton and Letters
- Anton and Chess CodeForces
- codeforces Anton and Fairy Tale
- codeforces 734 E. Anton and Tree (黑红树,缩点+dfs)
- Codeforces 734E. Anton and Tree By Assassin 缩点+树的最大直径
- Codeforces Round #379 (Div. 2)E. Anton and Tree(dfs缩点,想法题)
- Codeforces Round #379 (Div. 2) E. Anton and Tree —— 缩点 + 树上最长路
- Codeforces 734E Anton and Tree【并查集缩点+树的直径】好题~
- Codeforces 734E Anton and Tree (dfs缩点+树的直径)
- Codeforces 734E Anton and Tree【并查集缩点||DFS缩点+树的直径】
- [Codeforces734E]Anton and Tree 树的直径
- 【CodeForces734E】【缩点】Anton and Tree 题解
- 51nod-1434 区间LCM
- docker在windows 7上连接终端(ssh)
- How to switch xcode on Mac?
- Iterator new一个对象的过程
- 反射
- Anton and Tree CodeForces
- 众筹何以成为大众创业、万众创新的幕后英雄?
- Jzzhu and Sequences CodeForces
- FZU 2230 翻翻棋
- Unity 音频管理
- Bootsrap Table 分页
- HDU
- 行为树与状态机介绍
- 惯性动捕研发之路