Cod sursa(job #1877032)

Utilizator mihai.alphamihai craciun mihai.alpha Data 12 februarie 2017 20:50:47
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.62 kb
#include <bits/stdc++.h>

using namespace std;

FILE *fin = fopen("disjoint.in", "r");
FILE *fout = fopen("disjoint.out", "w");

#define BUF 1 << 17
char buf[BUF];
int pos = BUF;

inline char next()  {
    if(pos == BUF)
        fread(buf, 1, BUF, fin), pos = 0;
    return buf[pos++];
}

inline int read()  {
    int x = 0;
    char ch = next();
    while(!isdigit(ch))
        ch = next();
    while(isdigit(ch))
        x = x * 10 + ch - '0', ch = next();
    return x;
}

#define MAX 100001

struct disjoint  {
    private:
    int father[MAX];
    public:
    inline void construct(int N)  {
        for(int i = 1;i <= N;i++)
            father[i] = i;
    }
    inline int find(int x)  {
        int aux = x;
        while(aux != father[aux])
            aux = father[aux];
        while(x != aux)  {
            int aux1 = father[x];
            father[x] = aux;
            x = aux1;
        }
        return aux;
    }
    inline void unite(int x, int y)  {
        father[find(x)] = find(y);
    }
};

disjoint d;

int main()  {
    int N, M;
    N = read(), M = read();
    d.construct(N);
    for(int i = 1;i <= M;i++)  {
        int op, x, y;
        op = read(), x = read(), y = read();
        switch(op)  {
            case 1:
            d.unite(x, y);
            break;
            case 2:
            int u1, u2;
            u1 = d.find(x), u2 = d.find(y);
            if(u1 == u2)
                fprintf(fout, "DA\n");
            else
                fprintf(fout, "NU\n");
            break;
        }
    }
    fclose(fin);
    fclose(fout);
    return 0;
}