PAT_A1013#Battle Over Cities

Source:

PAT A1013 Battle Over Cities (25 分)

Description:

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 (<), 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

Keys:

Attention:

  • 逻辑上删除结点即可,即遍历到w时直接return

Code:

 1 /*
 2 Data: 2019-05-16 21:26:01
 3 Problem: PAT_A1013#Battle Over Cities
 4 AC: 24:40
 5 
 6 题目大意:
 7 给一个图,拿掉一个顶点及其边,问至少添加几条边,可以保证图的连通
 8 输入:
 9 第一行给出:结点数N<1e3,边数M,查询次数K
10 接下来M行,给出V1和V2,表示结点间存在边
11 接下来一行,依次给出破坏顶点序号(1~N),输出需要添加的边数
12 
13 */
14 #include<cstdio>
15 #include<algorithm>
16 using namespace std;
17 const int M=1e3+10,INF=1e9;
18 int grap[M][M],vis[M],n,m,k,w;
19 
20 void DFS(int u)
21 {
22     if(u==w)
23         return;
24     vis[u]=1;
25     for(int v=1; v<=n; v++)
26         if(vis[v]==0 && grap[u][v]==1)
27             DFS(v);
28 }
29 
30 int Travel()
31 {
32     int cnt=-1;
33     fill(vis,vis+M,0);
34     for(int i=1; i<=n; i++)
35     {
36         if(vis[i]==0 && i!=w)
37         {
38             DFS(i);
39             cnt++;
40         }
41     }
42     return cnt;
43 }
44 
45 int main()
46 {
47 #ifdef  ONLINE_JUDGE
48 #else
49     freopen("Test.txt", "r", stdin);
50 #endif // ONLINE_JUDGE
51 
52     scanf("%d%d%d", &n,&m,&k);
53     fill(grap[0],grap[0]+M*M, INF);
54     for(int i=0; i<m; i++)
55     {
56         int v1,v2;
57         scanf("%d%d",&v1,&v2);
58         grap[v1][v2]=1;
59         grap[v2][v1]=1;
60     }
61     for(int i=0; i<k; i++)
62     {
63         scanf("%d", &w);
64         printf("%d\n", Travel());
65     }
66 
67     return 0;
68 }

猜你喜欢

转载自www.cnblogs.com/blue-lin/p/10878338.html