Skip to content

Instantly share code, notes, and snippets.

@shiponcs
Last active June 8, 2020 03:47
Show Gist options
  • Save shiponcs/45c672a854d548532db1a054b32c51e5 to your computer and use it in GitHub Desktop.
Save shiponcs/45c672a854d548532db1a054b32c51e5 to your computer and use it in GitHub Desktop.
topic: DSU
#include <iostream>
using namespace std;
int link[5009], size[5009];
void init(int c)
{
for(int i = 0; i < c; i++) link[i] = i, size[i] = 1;
}
int root(int x)
{
while(x != link[x]) x = link[x];
return x;
}
bool same(int a, int b)
{
return root(a) == root(b);
}
void unite(int a, int b)
{
a = root(a);
b = root(b);
if(a < b) swap(a, b);
size[a] += size[b];
link[b] = a;
}
int main(){
int T,n,x,y,ans;
char c;
string s;
scanf("%d\n\n",&T);
for(int tc=1;tc<=T;tc++){
getline(cin,s);
n=s[0]-'A'+1;
ans=n;
init(ans);
while(1){
if(!getline(cin,s) || s.empty()) break;
x=s[0]-'A'; y=s[1]-'A';
if(!same(x, y)){
unite(x,y);
ans--;
}
}
if(tc!=1) printf("\n");
printf("%d\n",ans);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment