Wednesday, April 20, 2016

Solution of Uva 459 - Graph Connectivity

 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
 
#include<bits/stdc++.h>
using namespace std;
int p[100];
int prt(int z){
    if(p[z]==z) return z;
    else return p[z]=prt(p[z]);
}
int main()
{
    int i, t;
    scanf("%d\n", &t);
    while(t--){
        int x, m[50]={0}, mx=0, y, n, z;
        string s, a;
        set<int>ss;

        scanf("\n");
        getline(cin, a);
        n=(int)a[0]-64;

        for(i=1; i<=n; i++) p[i]=i;

        while(getline(cin, s)){
            if(s.size()==0) break;
            else{
                x=(int)s[0]-64;
                y=(int)s[1]-64;
                p[prt(y)]=prt(x);
            }
        }
        for(i=1; i<=n; i++) {
            p[i]=prt(i);
           ss.insert(p[i]);
        }
        cout<<ss.size()<<endl;
        if(t)cout<<endl;
    }
    return 0;
}

No comments:

Post a Comment