1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| #include <iostream> #include <cstdio> #include <algorithm> #include <cstring> using namespace std;
const int N = 1e6 + 10, M = N << 1; int h[N], e[M], ne[M], idx; int cir[N], tot, ed[N], cnt, fu[N]; int n, m, blk[N]; char str[N]; bool ins[N], vis[N], onc[N], abl[N];
void dfs_c(int x, int from) { ins[x] = vis[x] = true; for (int i = h[x]; ~i; i = ne[i]) { int j = e[i]; if (i == (from ^ 1)) continue; fu[j] = x; if (!vis[j]) dfs_c(j, i); else if (ins[j]){ for (int k = x; k != j; k = fu[k]) cir[++ cnt] = k, onc[k] = true; cir[++ cnt] = j, onc[j] = true; ed[++ tot] = cnt; if ((i & 1)) reverse(cir + ed[tot - 1] + 1, cir + ed[tot] + 1); } } ins[x] = false; }
void dfs_d(int x, int cirst, int dep, int sz) { abl[cirst + (dep % sz + sz) % sz] |= blk[x]; vis[x] = 1; for (int i = h[x]; ~i; i = ne[i]) { if (vis[e[i]] || onc[e[i]]) continue; dfs_d(e[i], cirst, dep - 1, sz); } }
void add(int a, int b) { e[idx] = b, ne[idx] = h[a], h[a] = idx ++; }
void link(int a, int b){add(a, b), add(b, a);} int get(int i, int j){return (i - 1) * m + j;}
int main() { int t;cin >> t; while (t --) { scanf("%d %d", &n, &m); idx = cnt = tot = 0; for (int i = 1; i <= n * m; ++ i) h[i] = -1, blk[i] = onc[i] = abl[i] = 0; for (int i = 1; i <= n; ++ i) { scanf("%s", str + 1); for (int j = 1; j <= m; ++ j) blk[get(i, j)] = str[j] == '0'; } for (int i = 1; i <= n; ++ i) { scanf("%s", str + 1); for (int j = 1; j <= m; ++ j) switch (str[j]) { case 'L' : link(get(i, j), get(i, j - 1));break; case 'R' : link(get(i, j), get(i, j + 1));break; case 'U' : link(get(i, j), get(i - 1, j));break; case 'D' : link(get(i, j), get(i + 1, j));break; } } for (int i = 1; i <= n * m; ++ i) vis[i] = 0; for (int i = 1; i <= n * m; ++ i) if (!vis[i]) dfs_c(i, -1); for (int i = 1; i <= n * m; ++ i) vis[i] = 0; for (int i = 1; i <= tot; ++ i) for (int j = ed[i - 1] + 1; j <= ed[i]; ++ j) dfs_d(cir[j], ed[i - 1] + 1, j - ed[i - 1] - 1, ed[i] - ed[i - 1]); int tblk = 0; for (int i = 1; i <= cnt; ++ i) tblk += abl[i]; printf("%d %d\n", cnt, tblk); } return 0; }
|