蓝桥杯JAVA版答案——历年真题——发现环(100分java版本)

问题描述
  小明的实验室有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);
			}
		}
	}
}

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值