Pagini recente » Cod sursa (job #2444668) | Cod sursa (job #2854915) | Cod sursa (job #1752138) | Cod sursa (job #524582) | Cod sursa (job #2793183)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
class graph{
vector< vector < int > > Ad;
const int nodes;
int edges = 0;
public:
graph( int n):nodes(n){ Ad.resize(nodes+1); }
graph( int n, int m, vector < vector < int > > & ad ) : nodes(n), edges(m){
Ad.resize(nodes+1);
for( int i = 1; i <= edges; ++i ){
for( int j = 0; j < ad[i].size(); ++i)
Ad[i].push_back(ad[i][j]);
}
}
void addEdge(int x, int y, bool oriented){
Ad[x].push_back( y );
if( oriented == false )
Ad[y].push_back(x);
edges++;
}
void DFS( int nod, bool vis[] ){
vis[nod] = 1;
for( int i = 0; i < Ad[nod].size(); ++i ){
int w = Ad[nod][i];
if( vis[w] == 0 )DFS(w,vis);
}
}
void BFS( int nod ){
queue < int > Q;
int dist[nodes] = {0};
Q.push(nod);
int x;
while( !Q.empty() ){
x = Q.front();
Q.pop();
for( int i = 0; i < Ad[x].size(); ++i ){
int w = Ad[x][i];
if( dist[w] == 0 && w != x && w != nod ){
dist[w] = dist[x] + 1;
Q.push(w);
}
}
}
for( int i = 1; i <= nodes; ++i )
if( dist[i] != 0 || i == nod )fout << dist[i] << ' ';
else fout << "-1 ";
}
int ConnectedComponents(){
int nr = 0;
bool vis[nodes] = {0};
for( int i = 1; i <= nodes; ++i )
if( vis[i] == 0 ){
DFS(i,vis);
nr++;
}
return nr;
}
};
const int NMAX = 100001;
struct disjoint_set{
int parent, sz;
} s[NMAX];
int Find(disjoint_set s[], int x){
int aux, root = x;
while( s[root].parent != root ) root = s[root].parent;
while( s[x].parent != x ){
aux = s[x].parent;
s[x].parent = root;
x = aux;
}
return root;
}
void Union(disjoint_set s[], int x, int y){
int root_x = Find(s,x);
int root_y = Find(s,y);
if( s[root_x].sz >= s[root_y].sz ){
s[root_x].sz += s[root_y].sz;
s[root_y].parent = root_x;
}
else{
s[root_y].sz += s[root_x].sz;
s[root_x].parent = root_y;
}
}
int main()
{
int N, M, task, x, y;
fin >> N >> M;
for( int i = 1; i <= N; ++i )
s[i] = {i,1};
for( int i = 1; i <= M; ++i ){
fin >> task >> x >> y;
if( task == 1 )
Union(s, x, y);
else ( Find(s, x) == Find(s, y) ) ? fout << "DA\n": fout << "NU\n";
}
return 0;
}