Pagini recente » Cod sursa (job #3244850) | Cod sursa (job #161449) | Cod sursa (job #1603766) | Cod sursa (job #1805157) | Cod sursa (job #1721187)
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
ifstream fin ("disjoint.in");
ofstream fout ("disjoint.out");
int n,m;
vector<int> ranks(10200);
vector<int> p(10200);
int find (int x)
{
int i;
int y;
for (i = x; p[i] != i; i = p[i]);
//path compression
for (;p[x] != x;)
{
y = p[x];
p[x] = i;
x = y;
}
return i;
}
void unify(int x, int y)
{
if (ranks[x] > ranks[y])
{
p[y] = x;
}
else if (ranks[x] < ranks[y])
p[x] = y;
else if (ranks[x] == ranks[y])
{
p[x] = y;
ranks[y] ++;
}
}
int main()
{
fin>>n>>m;
for (int i = 1; i <= n; i++)
{
ranks[i] = 1;
p[i] = i;
}
int x,y,c;
for (int i = 0; i <m; i++)
{
fin>>c>>x>>y;
if (c == 2)
{
if (find(x) == find(y))
fout<<"DA"<<endl;
else
fout<<"NU"<<endl;
}
else if (c == 1)
{
int px = find(x);
int py = find(y);
if (px == py)
{
cout<<i<<endl;
return 0;
}
unify(px, py);
}
}
return 0;
}