深度优先遍历求连通分量的个数。代码如下:
#include<cstdio>
#include<cstring>
using namespace std;
#define N 1001
int map[N][N];
int n;
void dfs(int * mark,int map[N][N],int node){
int i;
mark[node]=1;
for(i=1;i<=n;i++){
if(map[node][i]&&mark[i]==0)
dfs(mark,map,i);
}
}
int getN(int k){
int i;
int counter=0;
int mark[N];
memset(mark,0,sizeof(mark));
mark[k] = 1;
for(i=1;i<=n;i++){
if(mark[i]==0){
dfs(mark,map,i);
counter++;
}
}
return counter;
}
int main(){
int m,k;
int i,j;
int c1,c2;
memset(map,0,sizeof(map));
scanf("%d %d %d",&n,&m,&k);
for(i=0;i<m;i++){
scanf("%d %d",&c1,&c2);
map[c1][c2] = map[c2][c1] =1;
}
for(i=0;i<k;i++){
scanf("%d",&c1);
printf("%d\n",getN(c1)-1);
}
}