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);
}
}
}
图论算法 求强连通分量
最新推荐文章于 2020-07-06 13:33:39 发布