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.
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
思路
我们用dfs来判断连通性,就是用st数组,如果能遍历到的话,st我们就设为true,对于遍历不到的肯定是false。那么我们的答案就是没能遍历到的个数。
注意:
- 这道题的边数是 N ( N − 1 ) / 2 N(N-1)/2 N(N−1)/2 条,不然测试点 4 会报:段错误。
- 这道题最好用scanf,不然acwing过不了。
代码
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 1010,M = N*N;
int e[M],ne[M],h[N],idx;
int n,m,k;
bool st[N];
void add(int a,int b){
e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
void dfs(int u){
for(int i=h[u];~i;i=ne[i]){
int j=e[i];
if(st[j])continue;
st[j]=true;
dfs(j);
}
}
int main(){
cin>>n>>m>>k;
memset(h,-1,sizeof h);
for(int i=1;i<=m;i++){
int a,b;
cin>>a>>b;
add(a,b),add(b,a);
}
for(int i=1;i<=k;i++){
int x;
cin>>x;
for(int j=1;j<=n;j++){
st[j]=false;
}
st[x]=true;
int cnt=0;
for(int j=1;j<=n;j++){
if(!st[j]){
dfs(j);
cnt++;
}
}
cout<<cnt-1<<endl;
}
return 0;
}