1013 Battle Over Cities (25 分)-PAT甲级

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 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

 题目大意:给定一张城市地图,要求求出其中的一个城市被占领后要修的最少的道路,使剩余城市之间仍然连通。

 思路:1.对某城市被占领后的地图进行DFS搜索,求出连通分量的个数cnt,要使剩余城市之间仍然连通,要修的最少道路为cnt-1

2.要得到某城市被占领后的新地图(即删除被占领的城市及其与其他城市之间的道路),从邻接表中真正删除实现有一定难度(因为要重新构建图),所以我们可以对图进行抽象处理:DFS遍历的时候不对被占领的城市进行访问,这也就实现了“删除”操作。

3.得到连通分量的总个数:对图进行DFS搜索,根据DFS搜索的特点,如果图的所有顶点都是连通的,我们就能通过一次DFS操作实现遍历全部顶点,相反,如果一次DFS操作没能遍历所有顶点,那就说明没有遍历到的顶点不属于该连通分量,然后在对没有遍历到的顶点进行DFS搜索,直到所有顶点都被遍历到,这个过程中DFS的总次数就是连通分量的总个数。

AC代码 

#include 
#include 
using namespace std;
vector> city;
bool visited[1000];
void dfs(int cur,int occupied)
{
	if(cur==occupied||visited[cur])
		return;
	visited[cur]=true;
	for(int i=0;i>n>>m>>k;
	city.resize(n+1);
	int temp1,temp2;
	for(int i=1;i<=m;i++)//构造图 
	{
		cin>>temp1>>temp2;
		city[temp1].push_back(temp2);
		city[temp2].push_back(temp1);
	}
	int occupied,cnt;
	for(int i=0;i>occupied;
		fill(visited,visited+1000,false);//重置visited数组 
		cnt=0;
		for(int j=1;j<=n;j++)//求出有几个连通分量 
		{
			if(!visited[j]&&j!=occupied)
			{
				dfs(j,occupied);
				cnt++;
			}
		}
		cout<

更多PAT甲级题目:请访问PAT甲级刷题之路--题目索引+知识点分析(正在进行),感谢支持!

你可能感兴趣的:(PAT甲级刷题之路,c++,数据结构,深度优先,图论)