Pagini recente » Cod sursa (job #192954) | Cod sursa (job #3127874) | Cod sursa (job #182295) | Cod sursa (job #1080185) | Cod sursa (job #2794398)
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
ifstream f("disjoint.in");
ofstream g("disjoint.out");
int n,m;
int parinte[100001];
int get_parent(int x)
{
vector<int> met_on_the_way;
while (parinte[x] != 0)
{
met_on_the_way.push_back(x);
x = parinte[x];
}
for (auto el: met_on_the_way)
parinte[el] = x;
return x;
}
pair<int, int> get_parent_and_depth(int x)
{
int h = 0;
vector<int> met_on_the_way;
while (parinte[x] != 0)
{
met_on_the_way.push_back(x);
h++;
x = parinte[x];
}
for (auto el: met_on_the_way)
parinte[el] = x;
return {x,h};
}
int main()
{
f >> n >> m;
for (int i = 1; i <= n; i++)
parinte[i] = 0;
for (int i = 1; i <= m; i++)
{
int o,x,y;
f >> o >> x >> y;
if (o == 1)
{
pair<int,int> x_info = get_parent_and_depth(x);
pair<int,int> y_info = get_parent_and_depth(y);
int parinte_x = x_info.first;
int parinte_y = y_info.first;
int height_x = x_info.second;
int height_y = y_info.second;
// garanteaza ca nu se va intampla
// if (parinte_x == parinte_y)
if (height_x > height_y)
parinte[parinte_y] = parinte_x;
else
parinte[parinte_x] = parinte_y;
}
else
{
if (get_parent(x) == get_parent(y))
g << "DA\n";
else
g << "NU\n";
}
}
return 0;
}