迷宮城堡//強連通分支Tarjan
阿新 • • 發佈:2018-06-24
ria include align 單向 names tput rip pan 兩個
題目:
迷宮城堡
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; }
迷宮城堡//強連通分支Tarjan