NCPC 2015 A Adjoin the Networks(好题)

题目链接

http://codeforces.com/gym/100781/attachments

题意:给出n个点,m条边,问加一些边使所有点都能相互走通,问所有方案中最大距离的最小值是多少

树形dp,分别求出任意一个联通块中两点之间的最大距离,所以他们的半径变为(直径+1)/2,取所有联通块中距离最大的两个半径,再和连通图本身的最大值进行比较

#include <map>
#include <set>
#include <stack>
#include <queue>
#include <cmath>
#include <ctime>
#include <vector>
#include <cstdio>
#include <cctype>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
using namespace std;
#define INF 0x3f3f3f3f
#define inf -0x3f3f3f3f
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define mem0(a) memset(a,0,sizeof(a))
#define mem1(a) memset(a,-1,sizeof(a))
#define mem(a, b) memset(a, b, sizeof(a))
typedef long long ll;
const int maxn=100000+1000;
int a[maxn],vis[maxn],vis1[maxn],minv,head[maxn],tot,T;
struct Edge{
    int to,next;
}e[2*maxn];
void init(int n){
    tot=0,T=0;
    mem1(head),mem0(a),mem0(vis1),mem0(vis);
}
void addedge(int u,int v){
    e[tot].to=v,e[tot].next=head[u],head[u]=tot++,e[tot].to=u,e[tot].next=head[v],head[v]=tot++;
}
bool cmp(int u,int v){
    return u>v;
}
struct node{
    int u,dep;
};
node bfs(int u,int dep){
    queue<node>q;
    q.push((node){u,dep});
    vis[u]=T;
    int end1=u,count1=0;
    while(!q.empty()){
        node ans=q.front();
        q.pop();
        int u=ans.u,dep=ans.dep;
        for(int i=head[u];i!=-1;i=e[i].next){
            int v=e[i].to;
            if(vis[v]!=T){
                q.push((node){v,dep+1});
                vis[v]=T,end1=v,count1=dep+1;
            }
        }
    }
    node b={end1,count1};
    return b;
}
int main(){
    int n,m,u,v;
    while(scanf("%d%d",&n,&m)!=EOF){
        init(n);
        for(int i=0;i<m;i++){
            scanf("%d%d",&u,&v);
            u++,v++,vis1[u]=1,vis1[v]=1;
            addedge(u,v);
        }
        int cnt=0,minv=0,flag=0;
        for(int i=1;i<=n;i++){
            if(vis[i]==0&&vis1[i]!=0){
                ++T;    //注意这里要先++T,使得T不为0
                node b=bfs(i,0);
                ++T;
                node c=bfs(b.u,0);
                minv=max(minv,c.dep);
                a[cnt++]=(c.dep+1)/2;
                flag=1;
            }
        }
        sort(a,a+cnt,cmp);
        if(n<=2)
            printf("%d\n",n-1>=0?n-1:0);
        else if(flag==0)        //如果有n个连通块
            printf("2\n");
        else if(cnt>=3&&(a[0]==a[1])&&(a[1]==a[2]))
            printf("%d\n",max(minv,a[0]+a[1]+2));
        else
            printf("%d\n",max(minv,a[0]+a[1]+1));
    }
    return 0;
}


你可能感兴趣的:(NCPC 2015 A Adjoin the Networks(好题))