Codeforces - Anton and Tree

题目链接:Codeforces - Anton and Tree


显然,相同颜色可以缩点。然后变成一张相邻两点都不同的树。

多画一下可以发现答案就是树的直径/2.


AC代码:

#pragma GCC optimize("-Ofast","-funroll-all-loops")
#include<bits/stdc++.h>
//#define int long long
using namespace std;
const int N=2e5+10;
int f[N],n,c[N],x[N],y[N],p1,p2,d[N],mx,p;
vector<int> g[N];
int find(int x){return x==f[x]?x:f[x]=find(f[x]);}
inline int bfs(int s){
	queue<int> q;	q.push(s);	memset(d,-1,sizeof d);	d[s]=0; mx=0,p=s;
	while(q.size()){
		int u=q.front();	q.pop();
		for(auto to:g[u]){
			if(d[to]!=-1)	continue;
			d[to]=d[u]+1;	q.push(to);
			if(d[to]>mx)	mx=d[to],p=to;
		}
	}
	return p;
}
signed main(){
	ios::sync_with_stdio(false),cin.tie(nullptr);
	cin>>n;
	for(int i=1;i<=n;i++)	cin>>c[i],f[i]=i;
	for(int i=1;i<n;i++){
		cin>>x[i]>>y[i];	int fx=find(x[i]),fy=find(y[i]);
		if(c[fx]==c[fy])	f[fx]=find(fy);
	}
	for(int i=1;i<n;i++){
		int fx=find(x[i]),fy=find(y[i]);
		if(fx!=fy)	g[fx].push_back(fy),g[fy].push_back(fx);
	}
	p1=bfs(f[1]);	p2=bfs(p1);
	cout<<(mx+1)/2;
	return 0;
}
发布了553 篇原创文章 · 获赞 242 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_43826249/article/details/104168125