1. 程式人生 > 其它 >PAT甲級1013 Battle Over Cities (25 分)

PAT甲級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 city1city_1city1-city2city_2city2 and city1city_1city1-city3city_3city3. Then if city1city_1city1 is occupied by the enemy, we must have 1 highway repaired, that is the highway city2city_2city2-city3city_3city3.

Input Specification:

Each input file contains one test case. Each case starts with a line containing 3 numbers NNN (<1000<1000<1000), MMM and KKK, which are the total number of cities, the number of remaining highways, and the number of cities to be checked, respectively. Then MMM 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 NN

N. Finally there is a line containing KKK numbers, which represent the cities we concern.

Output Specification:

For each of the KKK 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
 
  
   
    
   
  
 
原始碼:
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
int map[1005][1005];
int visit[1005];
int n, m, k;
void bfs(int i){
        visit[i] = 1;
        for(int j = 1; j <= n; j ++){
            if(map[i][j] == 1 && visit[j] == 0){
                bfs(j);
            }
        }
}
int main(){
    cin>>n>>m>>k;
    for(int i = 0; i < m; i ++){
        int a, b;
        scanf("%d %d", &a, &b);
        map[a][b] = 1;
        map[b][a] = 1;
    }
    for(int i = 0; i < k; i ++){
        memset(visit, 0, sizeof(visit));
        int wc;
        scanf("%d", &wc);
        visit[wc] = 1;
        int rn = -1;
        for(int j = 1; j <= n; j ++){
            if(visit[j] != 1){
                bfs(j);
                rn ++;
            }
        }
        cout<<rn<<endl;
        visit[wc] = 0;
    }
}

已AC:在這裡插入圖片描述
易失分點:
不知道為啥遞迴dfs可以ac,但是用佇列的dfs過不了最後一個樣例,會超時