图论算法 求强连通分量

package com.bluecup.org;

import java.util.Scanner;
import java.util.TreeSet;

public class Tarjan {

	static int stack[] = new int[20];
	/**
	 * @param args
	 */
	static int n;
	static TreeSet<Integer>[] sets = new TreeSet[20];
	static boolean used[] = new boolean[20];
	static int low[] = new int[20];
	static int dfn[] = new int[20];

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scan = new Scanner(System.in);
		n = scan.nextInt();
		for (int i = 1; i <= n; i++) {
			sets[i] = new TreeSet<Integer>();
		}
		int i;
		do {
			i = scan.nextInt();
			int j = scan.nextInt();
			if (i > 0) {
				sets[i].add(j);
			}
		} while (i != 0);
		for (int ii = 1; ii <= n; ii++) {
			if (dfn[ii] == 0) {
				dfn(ii);
			}
		}
	}

	static int times;

	static int stop;
	static int flag[] = new int[20];

	private static void dfn(int v) {
		// TODO Auto-generated method stub
		times++;
		dfn[v] = low[v] = times;
		// System.out.println(sets[v].size());
		used[v] = true;
		stack[++stop] = v;
		int size = sets[v].size();
		while (sets[v].size() > 0) {
			int w = sets[v].pollFirst();
			if (dfn[w] == 0) {
				dfn(w);
				low[v] = Math.min(low[v], low[w]);

			} else if (used[w]) {
				low[v] = Math.min(low[v], dfn[w]);
			}
		}
		if (dfn[v] == low[v]) {
			System.out.println("-------------");
			int k;
			do {

				k = stack[stop--];
				used[k] = false;
				System.out.println(k);

			} while (k != v);
		}

	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值