[Topic link]
Https://codeforces.com/contest/475/problem/B
Algorithm
Run the Tarjan algorithm to determine if the number of strongly connected components is 1
Time complexity: O (NM)
Code
#include <bits/stdc++.h>using namespacestd;#defineMAXN 410structedge{intto, NXT;} E[MAXN* MAXN *2];intN, m, timer, CNT, tot, top;CharA[MAXN],B[MAXN];intHEAD[MAXN],DFN[MAXN * MAXN],LOW[MAXN * MAXN],S[MAXN *MAXN];BOOLINSTACK[MAXN *maxn];template<typename t> InlinevoidChkmax (T &x,t y) {x =Max (x, y);} Template<typename t> InlinevoidChkmin (T &x,t y) {x =min (x, y);} Template<typename t> InlinevoidRead (T &x) {T F=1; x =0; Charc =GetChar (); for(;!isdigit (c); c = GetChar ())if(c = ='-') F =-F; for(; IsDigit (c); c = GetChar ()) x = (x <<3) + (x <<1) + C-'0'; X*=F;} InlinevoidAddedge (intUintv) {Tot++; E[tot]=(Edge) {V,head[u]}; Head[u]=tot;} InlineintIdintXinty) { return(X-1) * m +y;} InlinevoidTarjan (intu) {Low[u]= Dfn[u] = + +timer; s[++top] =u; Instack[u]=true; for(inti = Head[u]; I i =e[i].nxt) { intv =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++; intv; Do{v= s[top--]; INSTACK[V]=false; } while(U! =v); }}intMain () {read (n); read (m); scanf ("%s%s", A +1, B +1); for(inti =1; I <= N; i++) { if(A[i] = ='<') { for(intj = m; J >1; j--) Addedge (ID (I,J), ID (i,j-1)); } Else { for(intj =1; J < M; J + +) Addedge (ID (I,J), id (i,j +1)); } } for(inti =1; I <= m; i++) { if(B[i] = ='v') { for(intj =1; J < N; J + +) Addedge (ID (j,i), id (j +1, i)); } Else { for(intj = N; J >1; j--) Addedge (ID (j,i), id (J-1, i)); }} Timer= CNT =0; for(inti =1; I <= n * m; i++) { if(!Dfn[i]) Tarjan (i); } if(CNT = =1) printf ("yes\n"); Elseprintf"no\n"); return 0; }
[Codeforces 475B] Strongly Connected City