Pagini recente » Cod sursa (job #2571061) | Cod sursa (job #2057623) | Cod sursa (job #2765242) | Clasament FMI No Stress 2012 | Cod sursa (job #2172454)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
ifstream f("disjoint.in" );
ofstream g("disjoint.out");
struct t_node
{
int v;
t_node* father;
};
t_node element[100005];
int n, m;
int inaltime[100005];
int reuniune(int x, int y)
{
t_node* actX = &element[x];
t_node* actY = &element[y];
while ( actX->father != NULL )
actX = actX->father;
while ( actY->father != NULL )
actY = actY->father;
if ( inaltime[actX->v] < inaltime[actY->v] )
swap(actX, actY);
inaltime[actX->v] = max(inaltime[actX->v], inaltime[actY->v] + 1);
actY->father = actX;
}
int query(int x, int y)
{
t_node* rootX = &element[x];
t_node* rootY = &element[y];
while ( rootX->father != NULL ) rootX = rootX->father;
while ( rootY->father != NULL ) rootY = rootY->father;
t_node* actX = &element[x];
t_node* actY = &element[y];
while ( actX->father != NULL )
{
actX->father = rootX;
actX = actX->father;
}
while ( actY->father != NULL )
{
actY->father = rootY;
actY = actY->father;
}
return actX == actY;
}
int main()
{
f >> n >> m;
for ( int i=1; i<=n; i++ )
{
element[i].v = 1;
element[i].father = NULL;
}
for ( int i=1; i<=m; i++ )
{
int tip, x, y;
f >> tip >> x >> y;
if ( tip == 1 )
{
reuniune(x, y);
}
else
{
g << (query(x, y)==1?"DA":"NU");
g << '\n';
}
}
}