[Codeforces 475B] Strongly Connected City
Posted evenbao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Codeforces 475B] Strongly Connected City相关的知识,希望对你有一定的参考价值。
[题目链接]
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; char a[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 void read(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 "); else printf("NO "); return 0; }
以上是关于[Codeforces 475B] Strongly Connected City的主要内容,如果未能解决你的问题,请参考以下文章