Pagini recente » Cod sursa (job #2081190) | Cod sursa (job #588514) | Cod sursa (job #1306211) | Cod sursa (job #2568327) | Cod sursa (job #2361732)
import java.lang.*;
import java.util.*;
import java.io.*;
class DisjointSet {
int value;
int rank;
DisjointSet parent;
DisjointSet(int value) {
this.rank = 0;
this.value = value;
this.parent = this;
}
public DisjointSet getRoot() {
if (this.parent == this)
return this;
// Compress the path
this.parent = this.parent.getRoot();
return this.parent;
}
public static void joinSets(DisjointSet first, DisjointSet second) {
if (first == second)
return;
if (first.rank == second.rank) {
++first.rank;
second.parent = first;
} else if (first.rank < second.rank) {
first.parent = second;
} else {
second.parent = first;
}
}
}
public class Main {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(new File("disjoint.in"));
PrintWriter out = new PrintWriter(new File("disjoint.out"));
int n = in.nextInt();
int m = in.nextInt();
// Construct the disjoint sets
DisjointSet[] sets = new DisjointSet[n];
for (int i = 0; i < n; ++i)
sets[i] = new DisjointSet(i + 1);
// Execute the operations
for (int i = 0; i < m; ++i) {
int opType = in.nextInt();
int x = in.nextInt();
int y = in.nextInt();
if (opType == 1)
DisjointSet.joinSets(sets[x - 1].getRoot(), sets[y - 1].getRoot());
else
out.println(sets[x - 1].getRoot() == sets[y - 1].getRoot() ? "DA" : "NU");
}
in.close();
out.close();
}
}