Cod sursa(job #1377625)

Utilizator dianaa21Diana Pislaru dianaa21 Data 5 martie 2015 23:10:16
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.87 kb
#include <fstream>
#define nmax 100001
using namespace std;
ifstream is ("disjoint.in");
ofstream os ("disjoint.out");

int N, M, x, y, type;
int GR[nmax], NR[nmax];

void Read();
int Find(int);
void Union(int,int);

int main()
{
    is >> N >> M;
    for(int i = 1; i <= N; ++i)
        GR[i] = i;

    for(int i = 1; i <= M; ++i)
    {
        is >> type >> x >> y;
        if(type == 1) Union(Find(x), Find(y));
        else {
            if(Find(x) == Find(y)) os << "DA\n";
            else os << "NU\n";
        }
    }
    is.close();
    os.close();
    return 0;
}
void Union(int x, int y)
{
    if(NR[x] > NR[y])
        GR[y] = x;
    if(NR[x] < NR[y])
        GR[x] = y;
    if(NR[x] == NR[y])
    {
        GR[y] = x;
        NR[x]++;
    }
}
int Find(int x)
{
    if(GR[x] == x)
        return x;
    return Find(GR[x]);
}