15发提交后仍然84WA求调
查看原帖
15发提交后仍然84WA求调
534589
S_Kuroko楼主2024/11/19 14:16
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=1e5+5;

vector<int> g[N];
int deep[N];
int fuqing[N];
int last[N],nxt[N];
int maxx=-1,loc1;
void dfs(int p,int fa)
{
	deep[p]=deep[fa]+1;
	if(deep[p]>=maxx)
	{
		maxx=deep[p];
		loc1=p;
	}
	for(int i=0;i<g[p].size();i++)
	{
		int to=g[p][i];
		if(to==fa) continue;
		dfs(to,p); 
	}
}
void dfs2(int p,int fa)
{
	deep[p]=deep[fa]+1;
	fuqing[p]=fa;
//	last[p]=fa;
//	nxt[fa]=p;
	if(deep[p]>=maxx)
	{
		maxx=deep[p];
		loc1=p;
	}
	for(int i=0;i<g[p].size();i++)
	{
		int to=g[p][i];
		if(to==fa) continue;
		dfs2(to,p); 
	}
}
void back(int p,int son,int end)
{
	while(1)
	{
		int ba=fuqing[p];
		
	}
	
}
int father,son;
int loc2;
int nowsearch;
int maxx2=-1;

int d1[N],d2[N];
int res=-1;

void DFS(int x,int fa)
{
	if(last[x]==fa||last[fa]==x) return ;
	d1[x]=0,d2[x]=0;
	for(int i=0;i<g[x].size();i++)
	{
		int to=g[x][i];
		if(x==nowsearch)
		{
			if(to==father||to==son) continue;
		}
		if(to==fa) continue;
		DFS(to,x);
		int t=d1[to]+1;
		if(d1[x]<t)
		{
			d2[x]=d1[x];
			d1[x]=t;
		}
		else if(t>d2[x])
		{
			d2[x]=t;
		}
	}
	res=max(res,d1[x]+d2[x]);
}

signed main()
{
//	freopen("1.in","r",stdin);
//	freopen("1.out","w",stdout);
	int n,k;
	cin>>n>>k;
	for(int i=1;i<n;i++)
	{
		int a,b;
		cin>>a>>b;
		g[a].push_back(b);
		g[b].push_back(a);
	}
	int s,t;
	dfs(1,0);
	s=loc1;
	memset(deep,0,sizeof deep);
	maxx=-1;
	dfs2(loc1,0);
	t=loc1;
	
//	cout<<s<<" "<<t<<endl;
	if(k==1)
	{
		cout<<2*(n-1)-(maxx-1)+1<<endl;
		return 0;
	}
	int now=t,erzi=0;
	while(1)
	{
		int ba=fuqing[now];
		nxt[now]=erzi;
		last[now]=ba;
		if(now==s) break;
		erzi=now;
		now=ba;
	}
	
	int ans=-1;
	loc2=s;
	last[s]=-1;
	nxt[t]=-1;
	for(int i=1;i<=maxx;i++)
	{
		nowsearch=loc2;
		father=last[loc2],son=nxt[loc2];
		
//		cout<<nowsearch<<" "<<father<<" "<<son<<endl;
		
		DFS(loc2,0);
		ans=max(ans,res);
		loc2=nxt[nowsearch];
	}
//	cout<<ans<<endl;
	cout<<min(2*(n-1)-(maxx-1)+1+1,2*(n-1)-(maxx-1)+1-ans+1)<<endl;
	
	return 0;
}
2024/11/19 14:16
加载中...