Cod sursa(job #3153237)

Utilizator Tudor06MusatTudor Tudor06 Data 28 septembrie 2023 18:01:58
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.53 kb
#pragma GCC optimize("Ofast,unroll-loops")
#pragma GCC target("avx2")
#include <fstream>
//#include <iostream>

using namespace std;

const int NMAX = 1e5;

int father[NMAX + 1];

int root( int node ) {
    int f, x, aux;
    for ( f = node; father[f] > 0; f = father[f] );
    for ( x = node; father[x] > 0; ) {
        aux = father[x];
        father[x] = f;
        x = aux;
    }
    return f;
}

class InParser {
private:
	FILE *fin;
	char *buff;
	int sp;

	char read_ch() {
		++sp;
		if (sp == 4096) {
			sp = 0;
			fread(buff, 1, 4096, fin);
		}
		return buff[sp];
	}

public:
	InParser(const char* nume) {
		fin = fopen(nume, "r");
		buff = new char[4096]();
		sp = 4095;
	}

	InParser& operator >> (int &n) {
		char c;
		n = 0;
		while (!isdigit(c = read_ch()));
		do {
			n = 10 * n + c - '0';
		} while (isdigit(c = read_ch()));
		return *this;
	}
};
int main() {
    InParser fin( "disjoint.in" );
    ofstream fout( "disjoint.out" );
    int n, q;
    fin >> n >> q;
    for ( int i = 1, a, b, tip; i <= q; i ++ ) {
        fin >> tip >> a >> b;
        switch( tip ) {
        case 1:
            a = root( a );
            b = root( b );
            if ( father[a] > father[b] ) swap( a, b );
            father[a] += father[b] - 1;
            father[b] = a;
            break;
        default:
            if ( root( a ) == root( b ) ) {
                fout << "DA\n";
            } else {
                fout << "NU\n";
            }
        }
    }
    return 0;
}