题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1269
tarjan算法可破,注意点和边的数量,MLE了1发。
1 #include <algorithm> 2 #include <iostream> 3 #include <iomanip> 4 #include <cstring> 5 #include <climits> 6 #include <complex> 7 #include <fstream> 8 #include <cassert> 9 #include <cstdio> 10 #include <bitset> 11 #include <vector> 12 #include <deque> 13 #include <queue> 14 #include <stack> 15 #include <ctime> 16 #include <set> 17 #include <map> 18 #include <cmath> 19 20 using namespace std; 21 22 const int maxn = 11111; 23 const int maxm = 100010; 24 typedef struct Edge { 25 int v; 26 int next; 27 Edge() { next = -1; } 28 }Edge; 29 30 int head[maxn], ecnt; 31 Edge edge[maxm]; 32 int n, m; 33 34 int bcnt, idx; 35 int dfn[maxn], low[maxn]; 36 int stk[maxn], top; 37 int group[maxn]; 38 bool instk[maxn]; 39 40 void init() { 41 memset(edge, 0, sizeof(edge)); 42 memset(head, -1, sizeof(head)); 43 memset(instk, 0, sizeof(instk)); 44 memset(dfn, 0, sizeof(dfn)); 45 memset(low, 0, sizeof(low)); 46 memset(group, 0, sizeof(group)); 47 ecnt = top = bcnt = idx = 0; 48 } 49 50 void adde(int uu, int vv) { 51 edge[ecnt].v = vv; 52 edge[ecnt].next = head[uu]; 53 head[uu] = ecnt++; 54 } 55 56 void tarjan(int u) { 57 int v = u; 58 dfn[u] = low[u] = ++idx; 59 stk[++top] = u; 60 instk[u] = 1; 61 for(int i = head[u]; ~i; i=edge[i].next) { 62 v = edge[i].v; 63 if(!dfn[v]) { 64 tarjan(v); 65 low[u] = min(low[u], low[v]); 66 } 67 else if(instk[v] && dfn[v] < low[u]) { 68 low[u] = dfn[v]; 69 } 70 } 71 if(dfn[u] == low[u]) { 72 bcnt++; 73 do { 74 v = stk[top--]; 75 instk[v] = 0; 76 group[v] = bcnt; 77 }while(v != u); 78 } 79 } 80 81 int main() { 82 // freopen("in", "r", stdin); 83 int uu, vv; 84 while(~scanf("%d %d", &n, &m) && n + m) { 85 init(); 86 for(int i = 0; i < m; i++) { 87 scanf("%d %d", &uu, &vv); 88 adde(uu, vv); 89 } 90 for(int i = 1; i <= n; i++) { 91 if(!dfn[i]) { 92 tarjan(i); 93 } 94 } 95 if(bcnt > 1) { 96 printf("No "); 97 } 98 else { 99 printf("Yes "); 100 } 101 } 102 return 0; 103 }