let's start Code

459 - Graph Connectivity

459 - Graph Connectivity

Topic: Union Find Algorithm

ডাটা স্ট্রাকচার: ডিসজয়েন্ট সেট(ইউনিয়ন ফাইন্ড)

Solution 01:



 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <bits/stdc++.h>
using namespace std;

#define INF 1<<30
#define MAX 10005
#define FASTIO ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);

int parent[100];

void Initialization(int n)
{
  for(int i = 0; i <= n; i++)
    parent[i] = i;
}

int find_parent(int x)
{
  if(parent[x] == x)return x;
  return parent[x] = find_parent(parent[x]);
}

void make_union(int x, int  y)
{
  parent[find_parent(x)] = find_parent(y);
}

bool isUnion(int x, int y)
{
  return find_parent(x) == find_parent(y);
}

int main()
{
 // FASTIO
   /*
    #ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
    freopen("error.txt", "w", stderr);
   #endif
    //*/
     int t,i , cs;
    bool space = false;
    scanf("%d",&t);
    getchar();
    for ( cs = 1 ; cs <= t ; cs++ , space = 1)
    {    if(space) printf("\n");
         char lim;
         string str;
        cin>>lim;
        getchar();
        Initialization(lim-'A');
        int ans = lim-'A' + 1;
        while(getline(cin,str) && str!="")
        {
           // cerr << str << endl;
            int x = str[0]-'A';
            int y = str[1]-'A';
            if(!isUnion(x,y)) make_union(x,y) , ans-- ;

        }
      
        cout<<ans<<endl;
    }
   return 0;
     //double end_time = clock();
    //printf( "Time = %lf ms\n", ( (end_time - start_time) / CLOCKS_PER_SEC)*1000);
}

Share:

No comments:

Post a Comment

About

let's start CODE

Popular Posts