玖雨y的算法刷题记录day08——图论
- 题目链接:冗余连接
- 题目思路:这道题也是考查并查集的题目,关键在于能不能反应过来,由于题目中明确指出 n 个节点 n 条边,要保留 n-1 条边,也就是说一定存在可以删除的边,并且题目中要求如果有多条候选边要选择最靠后的一条,根据并查集的初始化规则,每个节点的父节点都是自身,所以一定是先输入的边先构图,刚好满足题意。
import java.util.Scanner;
public class Main {
static int[] father;
public static void union(int x, int y) {
int fx = find(x);
int fy = find(y);
if (fx != fy) {
father[fx] = fy;
}
}
private static int find(int x) {
if (father[x] == x) return x;
else {
father[x] = find(father[x]);
return father[x];
}
}
public static boolean isSame(int x, int y) {
int fx = find(x);
int fy = find(y);
return fx == fy;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
father = new int[n + 1];
for (int i = 1; i < n + 1; i++) {
father[i] = i;
}
for (int i = 0; i < n; i++) {
int start = sc.nextInt();
int end = sc.nextInt();
if (isSame(start, end)) {
System.out.println(start + " " + end);
break;
} else {
union(start, end);
}
}
}
}