pta数据结构与算法题目集:7-25 朋友圈 (25 分)

本文介绍了一种使用并查集数据结构先对图进行连接操作,然后通过计算每个连通分量的顶点数量来确定最大度数的方法。通过实例展示了如何在输入n个节点和m条边的情况下,利用find_root和degree数组求解最大度数的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先使用并查集,后计数

#include <queue>
#include <cstdlib>
#include <cmath>
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <stack>
#include <map>
#include <set>
using namespace std;
typedef long long ll;

#define MAX 31111
const int INF = 0x3f3f3f3f;
const int maxn =  2*1e6+9;

int n,m;
int t;

int root[MAX];

int find_root(int pos)
{
	int i = pos;
	int temp = pos;
	
	while(root[pos] != pos)
		pos = root[pos];
		
	while(root[i] != pos)
	{
		temp = root[i];
		root[i] = pos;
		i = temp;
	}
	
	return pos;
}

int degree[MAX];
int main(void)
{
	int i,j,k;
	cin >> n >> m;
	
	for(i=0; i<=n; ++i)
		root[i] = i;
		
	for(i=0; i<m; ++i)
	{
		cin >> k;
		
		int a = 0;
		for(j=0; j<k; ++j)
		{
			int b = 0;
			cin >> b;
			
			if(j == 0)
				a = b;
			else
			{
				int temp_a = find_root(a);
				int temp_b = find_root(b);
				
				if(temp_a != temp_b)
					root[temp_b]= temp_a;
			}
		}
	}
	
	for(i=1; i<=n; ++i)
	{
		int pos = 0;
		pos = find_root(i);
		++degree[pos];
	}
		
	set<int> ans;
	
	for(i=1; i<=n; ++i)
		ans.insert(degree[i]);
		
	set<int>::iterator p = ans.end();
	
	--p;
	
	cout << *p << endl;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值