帮我解释一下这个思路为什么错了
查看原帖
帮我解释一下这个思路为什么错了
836448
stylus楼主2024/8/28 14:53

根据树的直径的结论,我以 1 为起点,寻找与 1 颜色相反的最远点,再以这个最远点寻找离它颜色相反的最远点,它们的距离就是结果。

这有什么问题吗?
附cpp:

#include<bits/stdc++.h>
#define int long long
using namespace std;
void read(int &x){
	x=0;bool f=0;char ch=getchar();
	while(ch>'9'||ch<'0'){
		if(ch=='-')f=1;
		ch=getchar();
	}do{x=(x<<3)+(x<<1)+(ch^48);ch=getchar();}while(ch>='0'&&ch<='9');
	x=f?-x:x;
}
int n,x,y,a[100001],st=1,mx;
vector<int>v[100001];
void dfs(int x,int f,int d){
	if(mx<d&&a[x]!=a[st])mx=d,st=x;
	for(int i:v[x]){
		if(i!=f)dfs(i,x,d+1);
	}return;
}
signed main(){
	read(n);
	for(int i=1;i<=n;i++)read(a[i]);
	for(int i=1;i<n;i++)read(x),read(y),v[x].push_back(y),v[y].push_back(x);
	dfs(1,0,0),dfs(st,0,0);
	cout<<mx;
	return 0;
}
2024/8/28 14:53
加载中...