Pagini recente » Cod sursa (job #774160) | Cod sursa (job #2464351) | Cod sursa (job #2697077) | Cod sursa (job #2897377) | Cod sursa (job #668706)
Cod sursa(job #668706)
// http://infoarena.ro/problema/disjoint
#include <fstream>
using namespace std;
const int MAXSIZE = 100001;
ifstream in("disjoint.in");
ofstream out("disjoint.out");
int length,operations;
int father[MAXSIZE];
void join(int first,int second);
int findAndUpdate(int node);
int main()
{
in >> length >> operations;
int type,first,second;
for(int i=1;i<=operations;i++)
{
in >> type >> first >> second;
if(type == 1)
join(findAndUpdate(first),findAndUpdate(second));
else
if(findAndUpdate(first) == findAndUpdate(second))
out << "DA\n";
else
out << "NU\n";
}
return (0);
}
void join(int first,int second)
{
father[first] = second;
}
int findAndUpdate(int node)
{
// daca s-a ajuns la radacina
// arborelui (nodul nu are tata)
if(!father[node])
return node;
else
{
// aplicam compresia drumurilor
// (legam nodul direct de radacina arborelui)
father[node] = findAndUpdate(father[node]);
return father[node];
}
}