Cod sursa(job #773468)

Utilizator PlayLikeNeverB4George Marcus PlayLikeNeverB4 Data 1 august 2012 19:01:43
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.28 kb
#include <cstdio>
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <sstream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <ctype.h>
#include <cstring>
#include <ctime>

using namespace std;

#define MAXN 100005
int N, M, cod, x, y;
int T[MAXN], R[MAXN];

void unite(int x, int y) {
    if(R[x] < R[y])
        T[x] = y;
    else if(R[x] > R[y])
        T[y] = x;
    else if(R[x] == R[y]) {
        T[x] = y;
        R[y]++;
    }
}

int find(int x) {
    int root = x;
    while(T[root] != root) root = T[root];

    for(int node = x; node != root; ) {
        int aux = T[node];
        T[node] = root;
        node = aux;
    }

    return root;
}

int main() {
	freopen("disjoint.in", "r", stdin);
	freopen("disjoint.out","w", stdout);

    scanf("%d %d", &N, &M);

    for(int i = 1; i <= N; i++)
        T[i] = i;

    for(int i = 0; i < M; i++) {
        scanf("%d %d %d", &cod, &x, &y);

        if(cod == 1)
            unite(find(x), find(y));
        else {
            if(find(x) == find(y))
                printf("DA\n");
            else
                printf("NU\n");
        }
    }

	return 0;
}