首页 > 其他分享 >1013 Battle Over Cities

1013 Battle Over Cities

时间:2022-10-31 23:55:05浏览次数:53  
标签:cities int Over visit highways Battle c2 c1 Cities

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

题意:先给你一张连通图,然后把其中一个结点删除,考虑剩下的结点需要几条线路可以实现连通,即求删除结点后的图中有几个连通分量

tip:dfs的时间复杂度为O(|V|+|E|),bfs的时间复杂度为O(|V|2),该题最后一个测试用例用bfs会超时而dfs不会,应该是顶点远大于边数导致的

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int n,m,k;
 4 int sum; //连通分量数
 5 int mmap[1005][1005];
 6 int visit[1005];
 7 void dfs(int start){
 8     visit[start]=1;
 9     for(int i=1;i<=n;++i){
10         if (mmap[start][i]==1&&visit[i]==0)
11             dfs(i);
12     }
13 }
14 void bfs(int start){ //会超时
15     queue<int> q;
16     q.push(start);
17     while(!q.empty()){
18         int temp=q.front();
19         visit[temp]=1;
20         q.pop();
21         for (int i=1;i<=n;++i){
22             if (mmap[temp][i]==1&&visit[i]==0)
23                 q.push(i);
24         }
25     }
26 }
27 void check(int c){
28     visit[c]=1; //剔除被占领的城市
29     for (int i=1;i<=n;++i){ //查询连通分量数
30         if (visit[i]==0){
31             bfs(i);
32             ++sum;
33         }
34     }
35 
36 }
37 
38 int main(){
39     memset(mmap,0,sizeof(mmap));
40     cin>>n>>m>>k;
41     int c1,c2;
42     for (int i=0;i<m;++i){
43         cin>>c1>>c2;
44         mmap[c1][c2]=1;
45         mmap[c2][c1]=1;
46     }
47     int c;
48     for (int i=0;i<k;++i){
49         cin>>c;
50         sum=0;
51         memset(visit,0,sizeof(visit));
52         check(c);
53         cout<<sum-1<<endl;
54     }
55 }

 

标签:cities,int,Over,visit,highways,Battle,c2,c1,Cities
From: https://www.cnblogs.com/coderhrz/p/16846365.html

相关文章