CF1335F Robots on a Grid

给出一个 $n\times m$ 的网格,每个格子有颜色,0 黑 1 白,每个格子还有一个方向,表示这个格子上的机器人会向那个方向走,它们同时开始运动,在任意时刻不能有两个机器人在同一个格子里
先最大化机器人个数,如果多种方案机器人个数相等,再最大化摆在黑格子里的机器人数量

建个图第一个就是所有环的大小,第二考虑某个环上一点,反向建边,走$\%siz$同余数的点都会碰到,看是否有黑色,就选它即可。

代码
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define pii pair<int, int>
#define mk make_pair
const int N = 1e6 + 10;
const int mod = 1e9 + 7;
int read()
{
int x = 0, f = 1;
char c = getchar();
while (c < '0' || c > '9')
{
if (c == '-')
f = -1;
c = getchar();
}
while (c >= '0' && c <= '9')
x = (x << 1) + (x << 3) + c - '0', c = getchar();
return x * f;
}
vector<int> g1[N], g2[N];
char s[N];
int maxx = 0, v[N], h[N], d[N], c[N], f[N], siz[N];
stack<int> st;
int cnt = 0;
void findmax(int x)
{
v[x] = cnt;
st.push(x);
for (int to : g1[x])
{
if (v[to] == cnt)
{
maxx = d[x] - d[to] + 1;

while (st.top() != to)
{
h[st.top()] = cnt;
st.pop();
}
h[to] = cnt;
}
else if (v[to] == 0)
d[to] = d[x] + 1, findmax(to);
}

}

void dfs(int x, int si)
{
if (c[x] == 0)
f[d[x] % si] = 1;
v[x] = 1;
for (int to : g2[x])
{
if (!v[to])
d[to] = d[x] + 1, dfs(to, si);
}
}
int main()
{
int T = read();
while (T--)
{
int n = read(), m = read();
int ans1 = 0, ans2 = 0;
for (int i = 1; i <= n * m; i++)
g1[i].clear(), g2[i].clear(), v[i] = d[i] = h[i] = 0;
cnt = 0;
for (int i = 1; i <= n; i++)
{
scanf("%s", s + 1);
for (int j = 1; j <= m; j++)
{
c[(i - 1) * m + j] = (s[j] == '1');
}
}
for (int i = 1; i <= n; i++)
{
scanf("%s", s + 1);
for (int j = 1; j <= m; j++)
{
int u = (i - 1) * m + j, v;
if (s[j] == 'U')
v = (i - 2) * m + j;
if (s[j] == 'D')
v = (i)*m + j;
if (s[j] == 'L')
v = (i - 1) * m + j - 1;
if (s[j] == 'R')
v = (i - 1) * m + j + 1;
g1[u].push_back(v);
g2[v].push_back(u);
}
}
for (int i = 1; i <= n * m; i++)
if (v[i] == 0)
{
cnt++;
maxx = 0;
while (!st.empty())
st.pop();
findmax(i);
siz[cnt] = maxx;
ans1 += maxx;
}
for (int i = 1; i <= n * m; i++)
v[i] = 0;
for (int i = 1; i <= n * m; i++)
if (v[i] == 0 && h[i] != 0)
{
int si = siz[h[i]];
for (int j = 0; j < si; j++)
f[j] = 0;
dfs(i, si);
for (int j = 0; j < si; j++)
ans2 += f[j];
}
cout << ans1 << " " << ans2 << endl;
}
}