[Codeforces 475B] Strongly Connected City
阿新 • • 發佈:2018-10-01
復雜度 else ted true fin for ins .com space
[題目鏈接]
https://codeforces.com/contest/475/problem/B
[算法]
建圖後運行Tarjan算法 , 判斷強連通分量數是否為1
時間復雜度 : O(NM)
[代碼]
#include<bits/stdc++.h> using namespace std; #define MAXN 410 struct edge { int to , nxt; } e[MAXN * MAXN * 2]; int n , m , timer , cnt , tot , top; chara[MAXN],b[MAXN]; int head[MAXN],dfn[MAXN * MAXN],low[MAXN * MAXN],s[MAXN * MAXN]; bool instack[MAXN * MAXN]; template <typename T> inline void chkmax(T &x,T y) { x = max(x,y); } template <typename T> inline void chkmin(T &x,T y) { x = min(x,y); } template <typename T> inline voidread(T &x) { T f = 1; x = 0; char c = getchar(); for (; !isdigit(c); c = getchar()) if (c == ‘-‘) f = -f; for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + c - ‘0‘; x *= f; } inline void addedge(int u,int v) { tot++; e[tot] = (edge){v,head[u]}; head[u]= tot; } inline int id(int x,int y) { return (x - 1) * m + y; } inline void tarjan(int u) { low[u] = dfn[u] = ++timer; s[++top] = u; instack[u] = true; for (int i = head[u]; i; i = e[i].nxt) { int v = e[i].to; if (!dfn[v]) { tarjan(v); low[u] = min(low[u],low[v]); } else if (instack[v]) low[u] = min(low[u],dfn[v]); } if (low[u] == dfn[u]) { cnt++; int v; do { v = s[top--]; instack[v] = false; } while (u != v); } } int main() { read(n); read(m); scanf("%s%s",a + 1,b + 1); for (int i = 1; i <= n; i++) { if (a[i] == ‘<‘) { for (int j = m; j > 1; j--) addedge(id(i,j),id(i,j - 1)); } else { for (int j = 1; j < m; j++) addedge(id(i,j),id(i,j + 1)); } } for (int i = 1; i <= m; i++) { if (b[i] == ‘v‘) { for (int j = 1; j < n; j++) addedge(id(j,i),id(j + 1,i)); } else { for (int j = n; j > 1; j--) addedge(id(j,i),id(j - 1,i)); } } timer = cnt = 0; for (int i = 1; i <= n * m; i++) { if (!dfn[i]) tarjan(i); } if (cnt == 1) printf("YES\n"); else printf("NO\n"); return 0; }
[Codeforces 475B] Strongly Connected City