Cod sursa(job #2927278)

Utilizator ioana.cCaprariu Ioana ioana.c Data 19 octombrie 2022 21:06:32
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.92 kb
#include <fstream>

using namespace std;

ifstream fin("disjoint.in");
ofstream fout("disjoint.out");

int n, m, c, x, y;
int t[100010], r[100010];

int find(int x){
	int r=x, y;
	//fout <<x;
	while(t[r] != r)
        r = t[r];
	while(t[x] != x){
		y = t[x];
		t[x] = r;
		x = y;
	}
	return r;
}

void Union(int x, int y){
	if(r[x] > r[y]) t[y] = x;
    else t[x] = y;
	if(r[x] == r[y]) r[y]++;
}

int main(){
    fin >> n >> m;
    for(int i=1; i<=n; i++){
        t[i] = i; r[i] = i;
    }
    for(int i=1; i<=m; i++){
        fin >> c >> x >> y;
        if(c == 1){
            if(find(x) == find(y)){
                fout << i;
                return 0;
            }
            Union(find(x), find(y));
        }
        else{
            if(find(x) == find(y))
                fout << "DA" << '\n';
            else
                fout << "NU" << '\n';
        }
    }
    return 0;
}