75pts求助,WA on#6#7#8#10#15
查看原帖
75pts求助,WA on#6#7#8#10#15
735763
_ChongYun_楼主2023/6/11 12:41
#include<bits/stdc++.h>
using namespace std;
struct node{
	int to,nxt,val;
}w[314514];      
int l1,l2;
int cnt=0; 
int s,n,k;
int fa[314514];
int h[314514]; 
int d[314514];
int dp1[314514],dp2[314514],maxi;
void Link(int x,int y,int z){
	++cnt;
	w[cnt].to=y;
	w[cnt].nxt=h[x];
	w[cnt].val=z;
	h[x]=cnt;
}
void dfs1(int x,int f,int cnt){
	if(cnt>l1){
		maxi=x;
		l1=cnt;
	}
	for(int i=h[x];i;i=w[i].nxt){
		int y=w[i].to;
		if(y==f){
			continue;
		}else{
			dfs1(y,x,cnt+1);
		}
	}
	return ;
}
bool dfs2(int x,int f){
	if(x==maxi) return true;
	for(int i=h[x];i;i=w[i].nxt){
		int y=w[i].to;
		if(y==f) continue;
		if(dfs2(y,x)){
			w[i].val=-1;
			return true;
		}
	}
	return false;
}
void dp(int x,int f){
	for(int i=h[x];i;i=w[i].nxt){
		int y=w[i].to;
		if(y==f){
			continue;
		}
		dp(y,x);
		if(dp1[y]+w[i].val>dp1[x]){
			dp2[x]=dp1[x];
			dp1[x]=dp1[y]+w[i].val;
		}else if(dp1[y]+w[i].val>dp2[x]){
			dp2[x]=dp2[y]+w[i].val;
		}
	}
}
int main(){
	cin>>n>>k;
	for(int i=1;i<=n-1;i++){
		int u,v;
		cin>>u>>v;
		Link(u,v,1);
		Link(v,u,1);
	}
	dfs1(1,0,0);
	l1=0;
	s=maxi;
	dfs1(s,0,0);
	if(k==1){
		cout<<2*n-l1-1<<endl;
	} 
	if(k==2){
		dfs2(s,0);
		dp(s,0);
		for(int i=1;i<=n;i++){
			l2=max(l2,dp1[i]+dp2[i]);
		}

		cout<<2*n-l1-l2<<endl;
	}
	return 0;
}
2023/6/11 12:41
加载中...