pat advanced 1013

地址:http://pat.zju.edu.cn/contests/pat-a-practise/1013

思路:通过dfs来判断图的联通性,通过N次dfs才遍历完图所有节点的话,那么就有N-1个不连同图。

参考代码:

#include
#include

int N, M, lost;
bool map[1000][1000], visited[1000];

void dfs(int start)
{
    for(int i = 1; i <= N; ++i)
    {
        if(i != lost && i != start && !visited[i] && map[start][i])
        {
            visited[i] = true;
            dfs(i);
        }
    }
}

int main()
{
    int K, c1, c2, cnt;
    scanf("%d %d %d", &N, &M, &K);
    for(int i = 0; i < M; ++i)
    {
        scanf("%d %d", &c1, &c2);
        map[c1][c2] = map[c2][c1] = true;
    }
    for(int i = 0; i < K; ++i)
    {
        scanf("%d", &lost);
        cnt = 0;
        memset(visited, 0, sizeof(visited));
        for(int j = 1; j<=N; ++j)
        {
            if(j != lost && visited[j]==false)
            {
                ++cnt;
                dfs(j);
            }
        }
        printf("%d\n", cnt-1);
    }
    return 0;
}


你可能感兴趣的:(Pat,ACM,c++)