题目:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 20588 Accepted Submission(s): 8962
#include <iostream> #include <vector> using namespace std; const int size = 1e4 + 1; vector<int> graph[size];//存图 int dfn[size]; int t = 0; int low[size]; int stack[size]; int pos = 0;//用于栈的索引 bool onstack[size];//是否在栈 bool marked[size]; int ans = 0;//连通分支数 void init(int N)//初始化 { t = 0; pos = 0; ans = 0; for(int i = 1; i <= N; i++) { graph[i].clear(); onstack[i] = false; marked[i] = false; } } void Tarjan(int x) { marked[x] = true; low[x] = dfn[x] = t++; onstack[x] = true; stack[pos++] = x; for(int i = 0; i < graph[x].size(); i++) { if(!marked[graph[x][i]])//未标记 { Tarjan(graph[x][i]); if(low[graph[x][i]] < low[x]) low[x] = low[graph[x][i]];//!!! } //在栈内 else if(onstack[graph[x][i]] && dfn[graph[x][i]] < low[x]) low[x] = dfn[graph[x][i]];//!!! } if(dfn[x] == low[x])//强连通分支的根 { ans++; while(stack[--pos] != x)//出栈 { int c = stack[pos]; onstack[c] = false; } onstack[x] = false; } } int main() { int N=1, M; int a, b; while(cin >> N >> M && N != 0 || M != 0) { //初始化 init(N); //输入 for(int i = 0; i < M; i++) { cin >> a >> b; graph[a].push_back(b); } for(int i = 1; i <= N; i++) { if(!marked[i]) Tarjan(1); } if(ans == 1) printf("Yes\n"); else printf("No\n"); } return 0; }
原文:https://www.cnblogs.com/w-j-c/p/9218975.html