Cod sursa(job #1183883)

Utilizator RazvanR104Razvan-Andrei Ciocoiu RazvanR104 Data 10 mai 2014 14:28:45
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.46 kb
#include <iostream>
#include <fstream>

#include <algorithm>
#include <bitset>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <utility>
#include <vector>

#if __cplusplus > 199711L
#include <unordered_map>
#include <unordered_set>
#endif

#include <cstdio>
#include <ctime>
#include <cmath>
#include <cstring>
#include <cstdlib>

using namespace std;

typedef long long int64;

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

const int NMAX = 100010;

int N, M;
int height[NMAX], linked_list[NMAX];

int _find(int x)
{
    int ret;
    for (ret = x; ret != linked_list[ret]; ret = linked_list[ret]);

    int y;
    for ( ; x != linked_list[x]; )
    {
        y = linked_list[x];
        linked_list[x] = ret;
        x = y;
    }

    return ret;
}

void unite(int x, int y)
{
    if (height[x] > height[y]) linked_list[y] = x;
    else linked_list[x] = y;

    if (height[x] == height[y]) ++height[y];
}

int main()
{
    int i, op, x, y;

    fin >> N >> M;

    for(i = 1; i <= N; ++i)
    {
        height[i] = 1;
        linked_list[i] = i;
    }

    while(M--)
    {
        fin >> op >> x >> y;

        switch(op)
        {
            case 1: unite(_find(x), _find(y)); break;
            case 2: if (_find(x) == _find(y)) fout << "DA\n";
                    else fout << "NU\n";
        }
    }

	fin.close();
	fout.close();
	return 0;
}