50pts求助
查看原帖
50pts求助
480015
是WXD楼主2022/10/30 10:19

rt

#include <cmath>
#include <queue>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#define ll long long
using namespace std;
int n,K;
ll ans,res;

inline ll re(){
	ll k=0,f=1ll;
	char cre=getchar();
	while(!('0'<=cre&&cre<='9')){
		if(cre=='-') f=-1ll;
		cre=getchar();
	}
	while('0'<=cre&&cre<='9'){
		k=(k<<1ll)+(k<<3ll)+(cre^48ll);
		cre=getchar();
	}
	return 1ll*k*f;
}

void wr(ll x){
	if(x<0){
		x=~x+1;
		putchar('-');
	}
	if(x>9) wr(x/10ll);
	putchar(x%10ll^48ll);
}

struct Edge{
	int v,w;
	int nex;
}E[100005<<1];

int head[100005],tote;
inline void add_edge(int u,int v){
	++tote;
	E[tote].v=v,E[tote].w=1,E[tote].nex=head[u],head[u]=tote;
}

int d[100005];
int pre[100005];
inline int bfs(int s){
	queue<int> q;
	memset(d,-1,sizeof(d));
	q.push(s);
	d[s]=0;
	while(q.size()){
		int x=q.front();
		q.pop();
		for(int i=head[x];i;i=E[i].nex){
			int v=E[i].v;
			if(d[v]==-1){
				d[v]=d[x]+1;
				pre[v]=i;
				q.push(v);
			}
		}
	}
	int p=s;
	for(int i=1;i<=n;++i) if(d[i]>d[p]) p=i;
	return p;
}

inline void modify(int x,int y){
	while(y!=x){
		int i=pre[y];
		E[i].w=E[i^1].w=-1;
		y=E[i^1].v;
	}
}

void dp(int x,int f){
	for(int i=head[x];i;i=E[i].nex){
		int v=E[i].v;
		if(v==f) continue;
		dp(v,x);
		int w=E[i].w;
		res=(res,d[x]+d[v]+w);
		d[x]=max(d[x],d[v]+w);
	}
}

int main(){
	tote=1;
	n=re(),K=re();
	for(int i=1;i<n;++i){
		int u=re(),v=re();
		add_edge(u,v);
		add_edge(v,u); 
	}
	int p=bfs(1);
	int q=bfs(p);
	ans=2*(n-1)-d[q]+1;
	if(K&1){
		wr(ans);
		return 0;
	}
	modify(p,q);
	memset(d,0,sizeof(d));
	dp(1,0);
	wr(ans-res+1);
	return 0;
}
/*

*/
2022/10/30 10:19
加载中...