PAT甲1013 Battle Over Cities 并查集/连通集/pair

题目描述

题目

Sample Input

3 2 3
1 2
1 3
1 2 3

Sample Output

1
0
0

思路

主要用并查集的思路。
相互连通的城市群构成一个集合,它们有相同的代表元(father)。
求出炸毁一个城市后,其他城市构成的并查集的个数n。如果想要这些城市群互相连通,只要再建造(n-1)条路即可。

AC代码

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

vector<pair<int,int> > roads; 
int father[1001]; 
/*
* find the father of vertex v 
*/ 
int findFather(int v){
	return father[v]==v?v:findFather(father[v]);
}

int main(){
	int N,M,K;
	cin>>N>>M>>K;
	//Input roads 
	for(int i = 0;i<M;++i){
		int vA,vB;
		cin>>vA>>vB;
		roads.push_back(pair<int,int>(vA,vB));
	}
	//Check
	for(int i = 1;i<=K;++i){
		//input the vertex to be deleted
		int delV;
		cin>>delV;
		//initialization
		for(int i = 1;i<=N;++i)
			father[i] = i;
		//create union-find sets 
		for(vector<pair<int,int> >::iterator it = roads.begin();it!= roads.end();++it){
			if((*it).first != delV && (*it).second != delV){
				int fatherA = findFather((*it).first),
					fatherB = findFather((*it).second);
				if(fatherA != fatherB){
					father[fatherB] = fatherA;
				}
			}	
		}
		//find the number of distinct sets
		vector<int> fathers; 
		for(int j = 1;j<=N;++j){
			if(j!=delV){
				int f = findFather(j);
				if(find(fathers.begin(),fathers.end(),f)== fathers.end())
					fathers.push_back(f);
			}
		}
		//Output 
		if(!fathers.empty())
			cout<<fathers.size()-1<<endl;
	}
	//if special cases 
	if(K == 0 || N == 0)
		cout<<0<<endl;	
	return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值