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;
}
### 数据结构PTA 题解 或 学习资料 在数据结构中,图是一种重要的抽象数据类型,广泛应用于各种实际问题的建模和求解。以下是一些图相关的PTA练习题及其解答思路[^1]: #### 1. 图的基本操作 - **7-35 城市间紧急救援 (25 point(s))** 该题目要求通过图的最短路径算法(如Dijkstra算法)来解决城市间的救援问题。需要考虑边权值的不同,并根据实际情况选择合适的路径。 ```python import heapq def dijkstra(graph, start): dist = {node: float('inf') for node in graph} dist[start] = 0 heap = [(0, start)] while heap: current_dist, u = heapq.heappop(heap) if current_dist > dist[u]: continue for v, weight in graph[u]: distance = current_dist + weight if distance < dist[v]: dist[v] = distance heapq.heappush(heap, (distance, v)) return dist ``` - **7-45 航空公司VIP客户查询 (25 point(s))** 这道题目涉及图的遍历(深度优先搜索或广度优先搜索),用于统计不同节点之间的连通性。 #### 2. 最短路径问题 - **7-37 模拟EXCEL排序 (25 point(s))** 虽然这道题目主要涉及排序,但其底层逻辑可以扩展到图的拓扑排序问题,尤其是有向无环图(DAG)中的应用。 - **7-38 寻找大富翁 (25 point(s))** 该题目可以通过构造邻接矩阵或邻接表表示图,然后使用Floyd-Warshall算法计算所有点对之间的最短路径。 #### 3. 图的连通性问题 - **7-25 朋友圈 (25 point(s))** 使用并查(Union-Find)算法来判断图中节点的连通性,适合处理动态变化的连通关系。 ```python parent = {} def find(u): if parent[u] != u: parent[u] = find(parent[u]) return parent[u] def union(u, v): pu, pv = find(u), find(v) if pu != pv: parent[pu] = pv ``` #### 4. 图的构建还原 - **7-23 还原二叉树 (25 point(s))** 虽然题目表面上是关于二叉树的构建,但实际上也可以视为一种特殊的图结构问题,利用前序、中序或后序遍历信息重建图。 - **7-24 树种统计 (25 point(s))** 该题目可以扩展到图的子结构统计问题,例如统计图中特定子图的数量。 #### 5. 图的应用 - **7-9 旅游规划 (25 point(s))** 这是一道典型的最短路径问题,通常使用Dijkstra算法或Bellman-Ford算法求解。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值