SDUT OJ 完美网络

完美网络

Time Limit: 1000 ms Memory Limit: 65536 KiB

Submit Statistic Discuss

Problem Description

完美网络是连通网络的基础上要求去掉网络上任意一条线路,网络仍然是连通网络。求一个连通网络要至少增加多少条边可以成为完美网络。

Input

第一行输入一个数T代表测试数据个数(T<=20)。每个测试数据第一行2个数n,m 分别代表网络基站数和基站间线路数。基站的序号为从1到n。接下来m行两个数代表x,y 代表基站x,y间有一条线路。

(0 < n < m < 10000)

Output

对于每个样例输出最少增加多少线路可以成为完美网络。每行输出一个结果。

Sample Input

2
3 1
1 2
3 2
1 2
2 3

Sample Output

扫描二维码关注公众号,回复: 2781625 查看本文章
2
1 

Hint

Source

中国海洋大学第三届“朗讯杯”编程比赛高级组试题

思路:完美网络是连通网络的基础上要求去掉网络上任意一条线路,网络仍然是连通网络,这就要求每个点的入度要>=2。所以在输入a,b的时候每个点都要先加1,然后进行排序,将入度<2的压入优先队列,之后对优先队列进行操作,每次取出两个元素(因为一条路径有两个点),然后两个自加1,sum也+1,然后讲入度小于2的继续压入优先队列中,直到就队列里剩下的点<2个。因为有1和0两种情况,所以要判断一下队列是否为空,当不为空是剩下的点肯定为1,要让他度为2,所以得加上1.最后输出cnt的值就行了

#include <iostream>
#include<stdio.h>
#include<queue>
#include<stdlib.h>
#include<string.h>
#include<algorithm>
using namespace std;
int a[10010];
int main()
{
    int n,m,i,sum;
    int t;
    cin>>t;
    while(t--)
    {
        sum=0;
        memset(a,0,sizeof(a));
        priority_queue<int,vector<int>,greater<int> >q;
        cin>>n>>m;
        for(i=0; i<m; i++)
        {
            int x,y;
            cin>>x>>y;
            a[x]++;
            a[y]++;
        }
        sort(a+1,a+1+n);
        for(i=1; i<=n; i++)
        {
            if(a[i]<2)
                q.push(a[i]);
            else break;
        }
        int a,b;
        while(q.size()>=2)
        {
            a=q.top();
            q.pop();
            b=q.top();
            q.pop();
            a++;
            b++;
            sum++;
            if(a<2)q.push(a);
            if(b<2)q.push(b);
        }
        if(!q.empty())
        {
            sum++;
            printf("%d\n",sum);
        }
        else printf("%d\n",sum);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41374539/article/details/81698947
今日推荐