标签:
---恢复内容开始---
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Swwubmission(s): 10884 Accepted Submission(s): 4878
import java.util.Scanner; import java.util.Stack; public class Targin { static class Edge{ //邻接表 int v; int next; //int weight; 这里不需要 } static int[] first;// first[]头结点数组 static int tot; static int n,m; //节点数,边数 static Edge[] edge; //边 static Stack<Integer> S; static boolean[] inStack; static int []DFN; //DFN[]为深搜次序数组(标记时间) static int []low; //Low[u]为u结点或者u的子树结点所能追溯到的最早栈中结点的次序号 static int Count,cnt; //Count记录强连通分量 public static void main(String[] args) { Scanner sc = new Scanner(System.in); while(sc.hasNext()){ n = sc.nextInt(); m = sc.nextInt(); if(n==0&&m==0) break; init(); int u,v; for(int i=0;i<m;i++){ u = sc.nextInt(); v= sc.nextInt(); addEdge(u,v); } //printGraph(); int cnt=0; for(int i=1;i<=n;i++){ if(DFN[i]==0){ Targin(i); } } //System.out.println(Count); if(Count>1) System.out.println("No"); else System.out.println("Yes"); } } private static void printGraph() { for(int i=1;i<=n;i++){ System.out.print(i); for(int e = first[i];e!=-1;e=edge[e].next){ System.out.print("->"); System.out.print(edge[e].v); } System.out.println(); } } private static void Targin(int u) { DFN[u] = low[u] = ++cnt; inStack[u] = true; S.add(u); //枚举边 for(int e = first[u];e!=-1;e=edge[e].next){ int v = edge[e].v; if(DFN[v]==0){ //j没被访问过 Targin(v); // 更新结点u所能到达的最小次数层 if(low[u]>low[v]) low[u]=low[v]; }else if(inStack[v]&&low[u]>DFN[v]){//如果v结点在栈内 low[u] = DFN[v]; } } if(DFN[u]==low[u]){ //如果节点u是强连通分量的根 Count++; int v; do{ v = S.pop(); inStack[v] = false; }while(u!=v); } } private static void init() { tot = 0; Count = 0; cnt =0; S = new Stack<Integer>(); edge = new Edge[m+1]; first = new int [n+1]; for(int i=1;i<=n;i++){ first[i] = -1; } DFN = new int [n+1]; low = new int[n+1]; inStack = new boolean[n+1]; } private static void addEdge(int u, int v) { //构建邻接表 edge[tot] = new Edge(); edge[tot].v = v; edge[tot].next = first[u]; first[u] = tot++; } }
---恢复内容结束---
标签:
原文地址:http://www.cnblogs.com/liyinggang/p/5043717.html