码迷,mamicode.com
首页 > 其他好文 > 详细

PAT1013: Battle Over Cities

时间:2017-10-08 19:00:44      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:一点   std   情况   names   emc   长度   air   cup   城市   

1013. Battle Over Cities (25)

时间限制
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

 

思路

这道题的本质问题其实就是求去掉某一点后的图有几个连通子图。那么需要重修的道路就是——连通子图数-1(保证余下节点全连通)。所以只要在去掉一个点后dfs下这个图确定连通子图个数就行。那么:

1.用一个数组表示点是否被遍历。

2.对于一个被入侵的城市city,只需要在dfs之前将这个城市标记为已遍历就行,这样dfs相当于只遍历去掉了这个点的图,即模拟了city从图中被去掉的情况。

代码

#include<iostream>
#include<vector>
using namespace std;

vector<vector<int>> graph(1000,vector<int>(1000,-1));

void dfs(const int city,const int num,vector<bool>& visits)
{
   visits[city] = true;
   for(int i = 1;i <= num;i++)
   {
       if(city == i)
        continue;
       if(graph[city][i] == 1 && !visits[i])
       {
           dfs(i,num,visits);
       }
   }
}

int main()
{
   int N,M,K;
   while(cin >> N >> M >> K)
   {
      while(M--)
      {
          int a,b;
          cin >> a >> b;
          graph[a][b] = graph[b][a] = 1;
      }

      while(K--)
      {
          int countRoad = 0;
          vector<bool> visits(N + 1,false);
          int city;
          cin >> city;
          visits[city] = true;
          for(int i = 1;i <= N;i++)
          {
              if(!visits[i])
              {
                  countRoad++;
                  dfs(i,N,visits);
              }
          }
          cout << countRoad - 1 << endl;
      }
   }
}

 

PAT1013: Battle Over Cities

标签:一点   std   情况   names   emc   长度   air   cup   城市   

原文地址:http://www.cnblogs.com/0kk470/p/7638132.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!