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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值