题意:给出很多个树,让你连接最少的边使整个图的直径最短。
思路:对每个树求出树的半径,然后将半径最大的树放在中间,然后将其他的树连接这个半径最大的树,求出ans即可。注意细节!
#include <iostream>
#include<string.h>
#include<vector>
#include<queue>
#include<algorithm>
#include<stdio.h>
#include<math.h>
#include<map>
#include<stdlib.h>
#include<time.h>
using namespace std;
typedef long long ll;
const int N=100010;
int head[N];
int ip;
struct edgenode
{
int to;
int next;
} tu[N*2];
void init()
{
ip=0;
memset(head,-1,sizeof(head));
}
void add(int u,int v)
{
tu[ip].to=v,tu[ip].next=head[u],head[u]=ip++;
}
bool vis[N]= {0};
int ans[105000];
int st,ed,len;
void dfs(int now,int pre,int sum)
{
vis[now]=1;
if(sum>len)len=sum,st=now;
for(int k=head[now]; k!=-1; k=tu[k].next)
{
int to=tu[k].to;
if(to!=pre)
dfs(to,now,sum+1);
}
}
int main()
{
int n,l;
init();
scanf("%d%d",&n,&l);
for(int i=0; i<l; i++)
{
int a,b;
scanf("%d%d",&a,&b);
add(a,b);
add(b,a);
}
int bj=0;
for(int i=0; i<n; i++)
if(!vis[i])
{
len=0;
st=i;
dfs(i,-1,0);
ed=st;
len=0;
dfs(st,-1,0);
ans[bj++]=len;
}
sort(ans,ans+bj);
if(bj>=3)
{
int hh;
hh=max(ans[bj-1],(ans[bj-1]+1)/2+(ans[bj-2]+1)/2+1);
hh=max(hh,(ans[bj-2]+1)/2+(ans[bj-3]+1)/2+2);
printf("%d\n",hh);
}
else if(bj==2)
{
int hh=max(ans[1],(ans[0]+1)/2+(ans[1]+1)/2+1);
printf("%d\n",hh);
}
else
printf("%d\n",ans[0]);
return 0;
}