【PAT甲级 - 1013】Battle Over Cities (25分)(并查集)

题干:

It is vitally important to have all the cities connected by highways in a war. If a city is occupied by the enemy, all the highways from/toward that city are closed. We must know immediately if we need to repair any other highways to keep the rest of the cities connected. Given the map of cities which have all the remaining highways marked, you are supposed to tell the number of highways need to be repaired, quickly.

For example, if we have 3 cities and 2 highways connecting city​1​​-city​2​​ and city​1​​-city​3​​. Then if city​1​​ is occupied by the enemy, we must have 1 highway repaired, that is the highway city​2​​-city​3​​.

Input Specification:

Each input file contains one test case. Each case starts with a line containing 3 numbers N (<1000), M and K, which are the total number of cities, the number of remaining highways, and the number of cities to be checked, respectively. Then M lines follow, each describes a highway by 2 integers, which are the numbers of the cities the highway connects. The cities are numbered from 1 to N. Finally there is a line containing K numbers, which represent the cities we concern.

Output Specification:

For each of the K cities, output in a line the number of highways need to be repaired if that city is lost.

Sample Input:

3 2 3
1 2
1 3
1 2 3

Sample Output:

1
0
0

题目大意:

给定n个点m条边的无向图,有k次询问,每次询问一个点,问去掉和这个点相连的所有的边以后,还需要添加几条边可以使得图为一个连通图。(n<1000)

解题报告:

这题掉坑了啊,,想当然以为m也<1000,因为这样才符合复杂度,但是这题其实没说m和k的复杂度,所以m最大可以到一个完全图n*(n-1)/2,也就是5e5左右,所以需要把边数开大一点才可以过。但是这样复杂度就不对了呀,,看了一下数据,大数据下k<20,也就是说查询很少,,所以预处理的话就非常不划算,因为PAT题经常容易数据水(??),所以直接暴力就行别预处理了。。。

AC代码:

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
#include<stack>
#include<map>
#include<vector>
#include<set>
#include<string>
#include<cmath>
#include<cstring>
#define FF first
#define SS second
#define ll long long
#define pb push_back
#define pm make_pair
using namespace std;
typedef pair<int,int> PII;
const int MAX = 2e6 + 5;
int n,m,k,u[MAX],v[MAX],f[MAX];
int getf(int v) {
	return f[v] == v ? v : f[v] = getf(f[v]);
} 
void merge(int u,int v) {
	int t1 = getf(u),t2 = getf(v);
	f[t2] = t1;
}
int main()
{
	cin>>n>>m>>k;
	for(int i = 1; i<=m; i++) {
		scanf("%d%d",u+i,v+i);
	}
	while(k--) {
		int tar,cnt = 0;
		scanf("%d",&tar);
		for(int i = 1; i<=n; i++) f[i] = i;
		for(int i = 1; i<=m; i++) {
			if(u[i] == tar || v[i] == tar) continue;
			merge(u[i],v[i]); 
		}
		for(int i = 1; i<=n; i++) {
			if(f[i] == i) cnt++;
		}
		printf("%d\n",max(cnt-2,0));
	}

	return 0 ;
}
发布了1106 篇原创文章 · 获赞 122 · 访问量 23万+

猜你喜欢

转载自blog.csdn.net/qq_41289920/article/details/104184388
今日推荐