Pagini recente » Cod sursa (job #2194113) | Cod sursa (job #2627217) | Cod sursa (job #434131) | Cod sursa (job #700673) | Cod sursa (job #2522702)
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Scanner;
public class Main {
private static final String INPUT_FILE = "disjoint.in";
private static final String OUTPUT_FILE = "disjoint.out";
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(new FileInputStream(INPUT_FILE));
PrintStream writer = new PrintStream(OUTPUT_FILE);
int n = scanner.nextInt();
int k = scanner.nextInt();
UnionFind unionFind = new UnionFind(n);
for (int i = 0; i < k; i++) {
int type = scanner.nextInt();
int a = scanner.nextInt();
int b = scanner.nextInt();
if (type == 1) {
unionFind.union(a, b);
} else if (type == 2) {
writer.println(unionFind.find(a) == unionFind.find(b) ? "DA" : "NU");
} else {
throw new IllegalArgumentException("Type is " + type);
}
}
}
private static class UnionFind {
private final int[] ids;
private final int[] sizes;
UnionFind(int n) {
ids = new int[n + 1];
sizes = new int[n + 1];
for (int i = 1; i <= n; i++) {
ids[i] = i;
sizes[i] = 1;
}
}
/* Find the id of x, executing path compression */
public int find(int x) {
while (ids[x] != x) {
int currId = ids[x];
ids[x] = ids[ids[x]];
x = currId;
}
return x;
}
/* Perform union on the sets of x and y */
public void union(int x, int y) {
int idX = find(x);
int idY = find(y);
/* Hold bigger tree in x */
if (sizes[idX] < sizes[idY]) {
int temp = idX;
idX = idY;
idY = temp;
}
if (idX != idY) {
ids[idY] = idX;
sizes[idX] += sizes[idY];
sizes[idY] = 0;
}
}
}
}