百度之星-degree

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40727946/article/details/81842020

degree

题目链接

Accepts: 1581

Submissions: 3494

Time Limit: 2000/1000 MS (Java/Others)

Memory Limit: 131072/131072 K (Java/Others)

Problem Description

度度熊最近似乎在研究图论。给定一个有 NNN 个点 (vertex) 以及 MMM 条边 (edge) 的无向简单图 (undirected simple graph),此图中保证没有任何圈 (cycle) 存在。

现在你可以对此图依序进行以下的操作:

  1. 移除至多 KKK 条边。
  2. 在保持此图是没有圈的无向简单图的条件下,自由的添加边至此图中。

请问最后此图中度数 (degree) 最大的点的度数可以多大呢?

Input

输入的第一行有一个正整数 TTT,代表接下来有几笔测试资料。

对于每笔测试资料: 第一行有三个整数 NNN, MMM, KKK。 接下来的 MMM 行每行有两个整数 aaa 及 bbb,代表点 aaa 及 bbb 之间有一条边。 点的编号由 000 开始至 N−1N - 1N−1。

  • 0≤K≤M≤2×1050 \le K \le M \le 2 \times 10^50≤K≤M≤2×10​5​​
  • 1≤N≤2×1051 \le N \le 2 \times 10^51≤N≤2×10​5​​
  • 0≤a,b<N0 \le a, b < N0≤a,b<N
  • 给定的图保证是没有圈的简单图
  • 1≤T≤231 \le T \le 231≤T≤23
  • 至多 222 笔测试资料中的 N>1000N > 1000N>1000

Output

对于每一笔测试资料,请依序各自在一行内输出一个整数,代表按照规定操作后可能出现的最大度数。

Sample Input

Copy

2
3 1 1
1 2
8 6 0
1 2
3 1
5 6
4 1
6 4
7 0

Sample Output

Copy

2
4

归类:并查集,图论。

题解:并查集寻找一共有几个集合,结果=集合数+最大度数+修改数。

代码

#include<stdio.h>
#include<string.h>
#include<math.h>
//#include <algorithm>
//using namespace std;

int n,m,k,num=0;
int per[300000];
int rank[300000];

void init()   
{
	for(int i=1;i<=n;i++)
	{
		per[i]=i;
		rank[i]=1;
	} 
	num=n;  		//记录一共有几个集合,初始化为n 
}
int find(int x)  
{
	if(x==per[x]) return x;  
	else return per[x]=find(per[x]);  
}
void unite(int x,int y)
{
	x=find(x);
	y=find(y);
	if(x==y) return ;
	else
	{
		if(rank[x]>rank[y]) per[y]=x;
		else
		{
			per[x]=y;
			if(rank[x]==rank[y]) rank[y]++; 
		} 
		num--;
	} 
} 

int min(int a,int b)
{
	int ans=(a<b)?a:b;
	return ans;
}

int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		memset(per,0,sizeof(per));
		memset(rank,0,sizeof(rank));
		scanf("%d%d%d",&n,&m,&k);
		init();
		int a[300000];
		memset(a,0,sizeof(a));
		for(int i=0;i<m;i++)
		{
			int x1,x2;
			scanf("%d%d",&x1,&x2);
			a[x1]++,a[x2]++;
			unite(x1,x2);
		}
		int Max=0;
		for(int i=0;i<300000;i++)
		{
			if(a[i]>Max)
			{
				Max=a[i];
			}
		} 
		int ans=min(n-1,Max+num-1+k);	//最大度数不能超过 n-1  
		printf("%d\n",ans);
	}
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/qq_40727946/article/details/81842020