CSU 1612: Destroy Tunnels strongly connected component Kosaraju algorithm, tunnelskosaraju
Link: zookeeper
Http://acm.csu.edu.cn/OnlineJudge/problem.php? Id = 1612
Give A matrix A the size of N * N, B = A ^ 1 + A ^ 2 + A ^ 3 + .... whether non-zero items exist in A ^ n and B.
The question can be converted to N vertices numbered 1-N. For any vertices, the question goes through any step to reach u (u is any of all vertices ). In Discrete Mathematics, matrix-related knowledge A ^ k represents the number of methods in the matrix from I to j in step k.
The question is to determine whether the entire graph is strongly connected.
After learning the Kosaraju algorithm, you can easily solve the problem. For details, see:
Http://www.cnblogs.com/tnt_vampire/archive/2010/04/12/1709895.html
Http://blog.csdn.net/dm_vincent/article/details/8554244
#include <algorithm>#include <iostream>#include <cstring>#include <cstdlib>#include <sstream>#include <cstdio>#include <vector>#include <cmath>#include <queue>#include <stack>#include <set>#include <map>#define lson o<<1, l, m#define rson o<<1|1, m+1, r#define PII pair<int, int>#define ALL(x) x.begin(),x.end()#define mem(a) memset(a,0,sizeof(a))typedef long long ll;const double pi = acos(-1.0);const int MAX = 0x3f3f3f3f;const ll mod = 1000000007ll;const int N = 1005;using namespace std; int T, n, x;int a[N][N], scc[N], cnt, v[N];vector <int> G[N], G2[N], S; void dfs1(int u) { if(v[u]) return; v[u] = 1; for(int i = 0; i < G[u].size(); i++) { dfs1(G[u][i]); } S.push_back(u);} void dfs2(int u) { if(scc[u]) return; scc[u] = cnt; for(int i = 0; i < G2[u].size(); i++) { dfs2(G2[u][i]); }} int main() { // freopen("in.txt", "r", stdin);// freopen("out.txt", "w", stdout); cin >> T; while(T--) { cin >> n; cnt = 0; mem(scc); mem(v); for(int i = 0; i < n; i++) { G2[i].clear(); G[i].clear(); } S.clear(); for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { scanf("%d", &x); if(x) { G[i].push_back(j); G2[j].push_back(i); } } } for(int i = 0; i < n; i++) { dfs1(i); } for(int i = n-1; i >= 0; i--) { if(!scc[S[i]]) { cnt++; dfs2(S[i]); } } puts(cnt == 1 ? "not exists" : "exists"); } return 0; }