问题描述
小明的实验室有N台电脑,编号1~N。原本这N台电脑之间有N-1条数据链接相连,恰好构成一个树形网络。在树形网络上,任意两台电脑之间有唯一的路径相连。
不过在最近一次维护网络时,管理员误操作使得某两台电脑之间增加了一条数据链接,于是网络中出现了环路。环路上的电脑由于两两之间不再是只有一条路径,使得这些电脑上的数据传输出现了BUG。
为了恢复正常传输。小明需要找到所有在环路上的电脑,你能帮助他吗?
输入格式
第一行包含一个整数N。
以下N行每行两个整数a和b,表示a和b之间有一条数据链接相连。
对于30%的数据,1 <= N <= 1000
对于100%的数据, 1 <= N <= 100000, 1 <= a, b <= N
输入保证合法。
输出格式
按从小到大的顺序输出在环路上的电脑的编号,中间由一个空格分隔。
样例输入
5
1 2
3 1
2 4
2 5
5 3
样例输出
1 2 3 5
稍微分析我们知道了这道题可以用并查集+dfs,或者拓扑排序来写, 网上有很多题解,但大多都是30分的,所以写了这个100分可以AC的代码
时间复杂度 0(n + m)
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;
public class Main{
static int N = 100010;
static int e[] = new int [N * 2];
static int h[] = new int [N];
static int ne[] = new int [N * 2]; //这里边数必须开二倍的空间不然会报错
static int d[] = new int [N];
static int n, k, idx;
static void add(int a, int b)
{
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
public static void main(String args[])
{
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
Arrays.fill(h, -1);
for (int i = 0; i < n; i++)
{
int a = scanner.nextInt(), b = scanner.nextInt();
add(a, b); add(b, a);
d[a]++; d[b]++;
}
String result = "";
topsort();
for (int i = 1; i < d.length; i++) if (d[i] > 1) result += i + " ";
System.out.println(result.trim());
scanner.close();
}
static void topsort()
{
LinkedList<Integer> list = new LinkedList<>();
for (int i = 1; i < d.length; i++)
if (d[i] == 1)
list.add(i);
while (!list.isEmpty())
{
int t = list.pop();
d[t] = 0;
for (int i = h[t]; i != -1; i = ne[i])
{
int j = e[i];
if (--d[j] == 1)
list.add(j);
}
}
}
}