1013. Battle Over Cities (25)

1.题目求当一个城市被敌人占领,还需要多少条公路才能把剩余的城市连通。可以使用并查集来求解。

2.采用邻接矩阵才不会超内存,一开始采用edge的结构体存储,结果出现段错误(内存超出要求)

3.采用并查集的方法,统计时,遇到破坏的城市则不处理,否则进行合并

4.最终检查并查集的集合数,集合数-2就是结果(集合数m减去破坏的城市,该城市为单独一个集合,即m-1,令n=m-1,剩下的集合数n,需要采用n-1条边才能连接起来)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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 city1-city2 and city1-city3. Then if city1 is occupied by the enemy, we must have 1 highway repaired, that is the highway city2-city3.

Input

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

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

 

//#include<string>
//#include <iomanip>
#include<vector>
#include <algorithm>
//#include<stack>
#include<set>
#include<queue>
#include<map>
//#include<unordered_set>
//#include<unordered_map>
//#include <sstream>
//#include "func.h"
//#include <list>
#include<stdio.h>
#include<iostream>
#include<string>
#include<memory.h>
#include<limits.h>
/*
1 0 1
1
输出 0

*/
using namespace std;
struct edgeNode{
	int a, b;
	edgeNode() :a(0), b(0){};
};
int find(int k, vector<int>&r)
{
	if (r[k] == k)
		return r[k];
	else
	{
		r[k] = find(r[k], r);
		return r[k];
	}
}
int main(void) {

	int n, m, k;
	cin >> n >> m >> k;
	n++;//城市从1开始,方便操作
	vector<vector<bool>> w(n, vector<bool>(n, false));//使用邻接矩阵存储,避免超时超内存,之前使用edge存储,结果段错误(超内存了)
	for (int i = 0; i < m; i++)
	{//输入边
		int a, b;
		cin >> a >> b;
		w[a][b] = true;
		w[b][a] = true;
	}
	for (int i = 0; i < k; i++)
	{
		int city;
		cin >> city;
		static vector<int> r(n, 0);
		for (int i = 0; i < n; i++)
			r[i] = i;
		//r[city] = 10000;
		for (int i = 1; i < n; i++)
		{
			if (i == city) continue;
			for (int j = i; j < n; j++)
			{
				if (j == city) continue;
				if (w[i][j])
					r[find(j, r)] = find(i, r);//否则合并两个城市
			}
		}
		int sum = -2;
		for (int i = 1; i < n; i++)
			if (r[i] == i) sum++;

		//如果只有1个城市,则不用修路了
		if (n-1 == 1)
			sum = 0;
		cout << sum << endl;
	}


	return 0;
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注