http://acm.hdu.edu.cn/showproblem.php?pid=1269
题目大意:给定一个图,判断该图是否是强连通图。(强连通图为从任意一点出发,可到达其他所有点)。深搜的Tarjin算法即可通过。其中
判断是否为强连通图需要判断所给的图是否连成一块儿,并且连接次数为n(所有点都可连接)。
#include <stdio.h> #include <algorithm> #include <string.h> #include <stack> #include <vector> using namespace std; #define N 10100 int Instack[N], dfn[N], low[N], block, cnt, Time, Top, my_Stack[N]; vector<vector<int> >G; int n, m; void Tra(int u) { dfn[u] = low[u] = ++Time; Instack[u] = 1; my_Stack[Top++] = u; int len = G[u].size(), v; for(int i=0; i<len; i++) { v = G[u][i]; if(!dfn[v]) { Tra(v); low[u] = min(low[u], low[v]); } else if(Instack[v]) low[u] = min(low[u], dfn[v]); } if(low[u]==dfn[u]) { block++; do { cnt++; v = my_Stack[--Top]; Instack[v] = 0; }while(u!=v); } } void Init() { memset(dfn, 0, sizeof(dfn)); memset(Instack, 0, sizeof(Instack)); memset(low, 0, sizeof(low)); memset(my_Stack, 0, sizeof(my_Stack)); G.clear(); G.resize(n+1); block = cnt = Time = Top = 0; } int main() { while(scanf("%d %d", &n, &m), m+n) { int a, b; Init(); for(int i=1; i<=m; i++) { scanf("%d %d", &a, &b); G[a].push_back(b); } Tra(1); if(block==1 && cnt==n)printf("Yes\n"); else printf("No\n"); } return 0; }