蓝桥杯——发现环(tarjan)

标题:发现环
小明的实验室有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

除了tarjan能解决之外,直接dfs也行

dfs方法:

将图存储到邻接矩阵中,建立一个数组du[]存储各个节点的度数

然后遍历找到一个度数<=1的节点,删去该节点(du[i]=-1)和与它相连的边,与它邻接的节点度数减一,继续找度数为1的节点放入队列q中,依次取队头元素,遍历找度数为1的节点,直到队列为空为止,遍历du数组找到不为-1的节点,这些节点就是一个环。

import java.util.ArrayList;
import java.util.Scanner;
import java.util.Stack;

public class tarjan发现环 {

	/**
	 * @param args
	 */
	static class edge{
		public int a;
		public int b;
		edge(int a,int b){
			this.a=a;
			this.b=b;
		}
	}
	static int dfn[];
	static int low[];
	static int clock=0;
	static Stack<Integer> s=new Stack<Integer>();
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		int n=sc.nextInt();
		ArrayList<edge>[] map=new ArrayList[n+1];
		for (int i = 0; i < map.length; i++) {
			map[i]=new ArrayList<edge>();
		}
		for (int i = 1; i <= n; i++) {
			int a=sc.nextInt();
			int b=sc.nextInt();
			//无向图要加入两个
			map[a].add(new edge(a,b));
			map[b].add(new edge(b,a));
		}
		//初始化dfn和low数组
		dfn=new int[n+1];
		low=new int[n+1];
		for (int i = 0; i <=n; i++) {
			dfn[i]=low[i]=-1;
		}
		//因为是无向图,所以要记录节点前驱防止  向回访问
		dfs(map,1,0);
	}
	/**
	 * 
	 * @param map 
	 * @param u 当前节点
	 * @param pre 前驱节点
	 */
	private static void dfs(ArrayList<edge>[] map, int start, int pre) {
		dfn[start]=low[start]=++clock;
		s.push(start);//当前节点入栈
		//遍历所有邻接节点
		for (int i = 0; i < map[start].size(); i++) {
			int temp=map[start].get(i).b;
			if(temp==pre){continue;}//如果是已访问过的前驱节点,直接跳过
			if(dfn[temp]==-1){//如果邻接节点temp没有访问过
				dfs(map,temp,start);
				low[start]=Math.min(low[start],low[temp]);
			}else {//由于是无向图,不用记录
				low[start]=Math.min(low[start],dfn[temp]);
			}
		}
		
		if(low[start]==dfn[start]){
			System.out.println("环为:");
			while (true) {
				int temp=s.pop();
				System.out.print(temp+" ");
				if(temp==start) break;
			}
			System.out.println();
		}
	}

}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值