Cod sursa(job #2427327)

Utilizator teoschipor00Teodora Schipor teoschipor00 Data 31 mai 2019 16:21:12
Problema Paduri de multimi disjuncte Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
#include <iostream>
#include <fstream>
#include <vector>
#define Nmax 100000
using namespace std;

///-----FISIERE-----
ifstream in("disjoint.in");
ofstream out("disjoint.out");

///-----TIPURI DE DATE-----
int tata[Nmax], grad[Nmax];


int FindFather(int nod)
{
    if(tata[nod] == nod)
        return nod;
    tata[nod] = FindFather(tata[nod]);
    return tata[nod];
}
void connect(int x, int y)
{
    int fx = FindFather(x);
    int fy = FindFather(y);
    if(fx == fy)
        return;
    if(grad[fx] > grad[fy])
    {
        tata[fy] = fx;
        grad[fx] += grad[fy];
    }
    else
    {
        tata[fx] = fy;
        grad[fy] += grad[fx];
    }
}
int main()
{
    ///-----CITIRE DATE DIN FISIER-----
    int N, M;
    in >> N >> M;
    for(int i = 1; i <= N; i++)
       { tata[i] = i;
	    grad[i] = 1;
       }
    int cod, x, y;
    for(int i = 0; i < M; i++)
    {
        in >> cod >> x >> y;
        int fx = FindFather(x);
        int fy = FindFather(y);
        if(cod == 1)
            connect(x, y);
        else if(fx == fy)
            out << "DA" << endl;
        else
            out << "NU" << endl;
    }
    return 0;
}