24h購物| | PChome| 登入
2012-06-21 14:34:46| 人氣2,005| 回應0 | 上一篇 | 下一篇

[UVA][并查集] 459 - Graph Connectivity

推薦 0 收藏 0 轉貼0 訂閱站台


 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.

picture22

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 and Output

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.

For each test case, 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



#include <stdio.h>
int p[26], r[26];
void init(int n) {
    while(n >= 0) {
        p[n] = n, r[n] = 1;
        n--;
    }
}
int find(int x) {
    return p[x] == x ? x : (p[x]=find(p[x]));
}
int joint(int x, int y) {
    x = find(x), y = find(y);
    if(x != y) {
        if(r[x] > r[y])
            r[x] += r[y], p[y] = x;
        else
            r[y] += r[x], p[x] = y;
        return 1;
    }
    return 0;
}
int main() {
    int t;
    char s[10];
    scanf("%d ", &t);
    while(t--) {
        gets(s);
        init(s[0]-'A');
        int ans = s[0]-'A'+1;
        while(gets(s)) {
            if(s[0] == '\0')
                break;
            ans -= joint(s[0]-'A', s[1]-'A');
        }
        printf("%d\n", ans);
        if(t)
            puts("");
    }
    return 0;
}

台長: Morris
人氣(2,005) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: UVA |
此分類下一篇:[UVA] 469 - Wetlands of Florida
此分類上一篇:[UVA][矩陣 D&C] 12470 - Tribonacci

是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文