UVA459 Graph Connectivity【并查集】

Consider a graph G formed from a large number of nodes connected by edges. G is said to be connected if a path can be found in 0 or more steps between any pair of nodes in G. For example, the graph below is not connected because there is no path from A to C.
    This graph contains, however, a number of subgraphs that are connected, one for each of the following sets of nodes: {A}, {B}, {C}, {D}, {E}, {A,B}, {B,D}, {C,E}, {A,B,D}
    A connected subgraph is maximal if there are no nodes and edges in the original graph that could be added to the subgraph and still leave it connected. There are two maximal connected subgraphs above, one associated with the nodes {A, B, D} and the other with the nodes {C, E}.
在这里插入图片描述
    Write a program to determine the number of maximal connected subgraphs of a given graph.
Input
The input begins with a single positive integer on a line by itself indicating the number of the cases following, each of them as described below. This line is followed by a blank line, and there is also a blank line between two consecutive inputs.
    The first line of each input set contains a single uppercase alphabetic character. This character represents the largest node name in the graph. Each successive line contains a pair of uppercase alphabetic characters denoting an edge in the graph.
The sample input section contains a possible input set for the graph pictured above.
Input is terminated by a blank line.
Output
For each test case, write in the output the number of maximal connected subgraphs. The outputs of two consecutive cases will be separated by a blank line.
Sample Input
1

E
AB
CE
DB
EC

Sample Output
2

问题链接UVA459 Graph Connectivity
问题简述:(略)
问题分析
    计算连通子图的数量。
程序说明
    并查集模板题,需要注意输入格式。
    使用函数fgets()要好于用函数gets(),编译时不会出警告,但是用法有所不同,关键在参数和字符串缓冲区的内容上。并查集模板中增加变量fcnt,大大增加了代码的简洁性。
参考链接:(略)
题记:(略)

AC的C++语言程序如下:

/* UVA459 Graph Connectivity */

#include <bits/stdc++.h>

using namespace std;

const int EN = 4;
const int N = 26;
int f[N], fcnt;

void UFInit(int n)
{
    for(int i = 0; i < n; i++)
        f[i] = i;
    fcnt = n;
}

int Find(int a) {
    return a == f[a] ? a : f[a] = Find(f[a]);
}

void Union(int a, int b)
{
    a = Find(a);
    b = Find(b);
    if (a != b) {
        f[a] = b;
        fcnt--;
    }
}

int main()
{
    int n;
    char lnn[2], e[EN];    // 最大结点数的大写字母,边(2个大写字母)
    scanf("%d", &n);
    while(n--) {
        scanf("%s", lnn);
        getchar();
        UFInit(lnn[0] - 'A' + 1);

        while(fgets(e, EN, stdin) && e[0] != '\n')
            Union(e[0] - 'A', e[1] - 'A');

        printf("%d\n", fcnt);
        if(n) printf("\n");
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/tigerisland45/article/details/89742306