1013 Battle Over Cities (25 分)

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

中文翻译:

战争时城市之间需要互通高速公路。一旦一座城市被敌军占领,通向这座城市的所有高速公路都将被关闭。我们必须马上了解到我们是否需要修哪些高速以保证剩下的城市之间互连。给出城市地图,这个地图里现存的高速都被标出了,你需要快速求出需要修的高速的个数。

例如,如果我们有三个城市和两个高速公路“城市1-城市2”以及“城市1-城市3”,则如果城市1被敌军占领,我们需要将一条高速修好,这个高速是“城市2-城市3”。

输入规范:

每个输入文件有一个测试case,每个case开始输入三个数N(

输出规范:

对于这K个城市,输出一旦这个城市沦陷时需要修的高速的个数。

 

分析:

这题实际上是考察连通图,当一个连通图被删掉一个节点变为t个联通分量的时候,只需要添加t-1个线就能让这些联通分量连接在一起。这里,我们使用深度优先搜索对每个图上的节点进行便利,对搜索到的节点进行标记,标记节点记为visit[i]。我们需要了解深搜dfs和广搜bfs都只是一种搜索手段。两种方法都可以用在这里。

我们的代码使用深度优先搜索dfs,代码如下(参考柳神):

#include
#include

using namespace std;
int visit[1000];
int v[1000][1000]={0};
int n;
void dfs(int node){
  visit[node]=1;
  for(int i=1;i<=n;i++){
   if(visit[i]==0&&v[node][i]==1)
      dfs(i);
  }
}


int main(){
  int m,k; //n represents the number of the city, m represents the number of highway, k represent the number of the interested cities.
  scanf("%d %d %d",&n,&m,&k);
  for(int i=0;i

你可能感兴趣的:(PAT)