pat 1013. Battle Over Cities (25)

本文详细解析PAT A 1013题目的解决方案,使用C++实现并查集算法处理图论问题。通过输入顶点数量、边的数量以及询问次数,程序能够判断图中除了特定顶点外其余顶点是否连通,并输出连通分量的数量。

https://www.patest.cn/contests/pat-a-practise/1013


代码来自http://blog.youkuaiyun.com/jtjy568805874/article/details/50791941


#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
typedef struct edge {
	int x, y;
	void read() { scanf("%d %d",&x,&y); }
}Edge;

int f[1001];
int find(int x) {
	return x == f[x] ? x : f[x] = find(f[x]);
}

int main()
{
	int n, m, k, c;
	scanf("%d %d %d", &n, &m, &k);
	vector<Edge> edges(m);
	for (int i = 0; i < m; i++) edges[i].read();
	while (k--) {
		scanf("%d", &c);
		for (int i = 0; i <= 1000; i++) f[i] = i;
		int need = n - 2;
		for (int i = 0; i < m && need >0; i++)
		{
			if (edges[i].x == c || edges[i].y == c) continue;
			int fx = find(edges[i].x), fy = find(edges[i].y);
			if (fx == fy) continue; else { f[fy] = fx; need--; }
		}
		printf("%d\n", max(need, 0));
	}
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值