Cod sursa(job #2804066)

Utilizator andrei_marciucMarciuc Andrei andrei_marciuc Data 20 noiembrie 2021 20:01:37
Problema Paduri de multimi disjuncte Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.49 kb
#include <stdio.h>

FILE *fin;

void swap( int& a, int& b ) {
	int aux = a;
	a = b;
	b = aux;
}

int poz, sizeBuff;
char buff[ ( 1 << 12 ) ];
char nextChar() {
	if( poz == sizeBuff ) {
		fread( buff, 1, sizeBuff, fin );
		poz = 0;
	}

	return buff[ poz++ ];
}

bool type[ 100 ];
int readInt() {
	int rez = 0, ch;
	while( !type[ ch = nextChar() ] );
	do
		rez = rez * 10 + ch - '0';
	while( type[ ch = nextChar() ] );

	return rez;
}

#define MAX 100010

int tata[ MAX ];

int Tata( int x ) {
	while( tata[ x ] != x )
		x = tata[ x ];

	return x;
}

int Tata2( int x, const int& y ) {
	int yy;
	while( tata[ x ] != x ) {
		yy = tata[ x ];
		tata[ x ] = y;
		x = yy;

	}

	return x;
}

void reuniune( int x, int y ) {
	y = Tata( y );
	tata[ Tata2( x, y ) ] = y;
}

bool fac_parte_din_aceeai_multime( int x, int y ) {
	return Tata( x ) == Tata( y );
}

int n, q;
char rez[ 2 ][ 4 ] = { "NU\n", "DA\n" };

int main()
{
	sizeBuff = sizeof( buff );
	type[ '0' ] = type[ '1' ] = type[ '2' ] = type[ '3' ] = type[ '4' ] = 1;
	type[ '5' ] = type[ '6' ] = type[ '7' ] = type[ '8' ] = type[ '9' ] = 1;
	fin = fopen( "disjoint.in", "r" );
	fread( buff, 1, sizeBuff, fin );
	n = readInt();
	q = readInt();
	for( int i = 1; i <= n; i++ )
		tata[ i ] = i;

	int op, x, y;
	FILE *fout = fopen( "disjoint.out", "w" );
	while( q-- ) {
		op = readInt();
		x = readInt();
		y = readInt();
		if( op == 1 )
			reuniune( x, y );
		else fputs( rez[ fac_parte_din_aceeai_multime( x, y ) ] + '\0', fout );
	}
	fclose( fin );
	fclose( fout );
	return 0;
}