Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- class UF{
- public:
- int *a, *sz;
- int n;
- UF(int n){
- sz = new int[n];
- a = new int[n];
- this->n = n;
- for(int i =0 ; i < n; i++)
- a[i] = i, sz[i] = 1;
- }
- ~UF(){
- delete sz;
- delete a;
- }
- int root(int p){
- while(a[p] != p) {
- a[p] = a[a[p]];
- p = a[p];
- }
- return p;
- }
- void merge(int p, int q){
- int i = root(p);
- int j = root(q);
- if(i == j) return;
- if(sz[i] > sz[j]) a[j] = i, sz[i] += sz[j];
- else a[i] = j, sz[j] += sz[i];
- }
- bool find(int p, int q){
- return root(p) == root(q);
- }
- };
- int main(){
- //ios_base::sync_with_stdio(false);
- //cin.tie(NULL);
- int x,y;
- UF *uf = new UF(100001);
- int total = 0;
- while(cin >> x){
- if(x == -1){
- cout << total << endl;
- total = 0;
- delete uf;
- uf = new UF(100001);
- continue;
- }
- cin >> y;
- if(uf->find(x,y)) total++;
- else{
- uf->merge(x,y);
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement