WA24分求调
查看原帖
WA24分求调
1366699
programmer330楼主2024/11/27 08:34
#include<bits/stdc++.h>
using namespace std;
#define N 100100 
struct node{
	int to,w,nxt;
}edge[2*N];
int n,k,q,p,tot=-1,ans,ans1,ans2,head[N],d[N],father[N];
void addedge(int x,int y){
	tot++;
	edge[tot].to=y;
	edge[tot].w=1;
	edge[tot].nxt=head[x];
	head[x]=tot;
}

void dfs1(int x,int fa,int s){
	if(s>ans){
		ans=s;
		p=x;
	}
	for(int i=head[x];i!=-1;i=edge[i].nxt){
		if(edge[i].to!=fa){
			dfs1(edge[i].to,x,s+edge[i].w);
		}
	}
}
void dfs2(int x,int fa,int s){
	if(s>ans1){
		ans1=s;
		p=x;
	}
	for(int i=head[x];i!=-1;i=edge[i].nxt){
		if(edge[i].to!=fa){
			father[edge[i].to]=x;
			dfs2(edge[i].to,x,s+edge[i].w);
		}
	}
}

void dp(int x,int fa){
	for(int i=head[x];i!=-1;i=edge[i].nxt){
		int y=edge[i].to;
		if(y==fa)continue;
		dp(y,x);
		ans2=max(ans2,d[x]+d[y]+edge[i].w);
		d[x]=max(d[x],d[y]+edge[i].w);
	}
}

void change(int x,int y){
	if(x==y)return;
	for(int i=head[x];i!=-1;i=edge[i].nxt){
		if(edge[i].to==father[x]){
			edge[i].w=-1;
			edge[i^1].w=-1;
			change(edge[i].to,y);
		}
	}
}

int main(){
	int x,y;
	memset(head,-1,sizeof head);
	scanf("%d%d",&n,&k);
	for(int i=1;i<n;i++){
		scanf("%d%d",&x,&y);
		addedge(x,y);
		addedge(y,x);
	}
	dfs1(1,0,0);
	dfs2(p,0,0);
	if(k==1){
		printf("%d\n",2*(n-1)-ans1+1);
		return 0;
	}
	change(q,p);
	dp(1,0);
	printf("%d\n",2*(n-1)-ans1-ans2+2);
	

	return 0;
}
2024/11/27 08:34
加载中...