题面
解法
用网络流来调整有向图的度数
- 显然可以看出最后整张图一定由若干个环构成,并且环之间不会出现连边
- 那么,我们可以对于每一个格子建一个入点和出点,分别表示该点的入度情况和出度情况
- 所以,我们可以将 S S 和所有点的入点连边,容量为,费用为 0 0 ;将所有点的出点和连边,容量为 1 1 ,费用为
- 然后对于这个格子的四周四个格子,由该点的入点连向周围的点的出点,容量为 1 1 ,如果方向和原来方向一致,费用为,否则费用为 1 1 <script type="math/tex" id="MathJax-Element-215">1</script>
- 然后跑最小费用最大流即可
代码
#include <bits/stdc++.h>
#define N 20
using namespace std;
template <typename node> void chkmax(node &x, node y) {x = max(x, y);}
template <typename node> void chkmin(node &x, node y) {x = min(x, y);}
template <typename node> void read(node &x) {
x = 0; int f = 1; char c = getchar();
while (!isdigit(c)) {if (c == '-') f = -1; c = getchar();}
while (isdigit(c)) x = x * 10 + c - '0', c = getchar(); x *= f;
}
const int M = N * N * 2;
struct Edge {
int next, num, c, w;
} e[N * M];
int dx[5] = {0, -1, 1, 0, 0}, dy[5] = {0, 0, 0, -1, 1};
int n, m, s, t, cnt, a[N][N];
int dis[M], pre[M], las[M], used[M];
int calc(int x, int y) {return (x - 1) * m + y;}
int num(char c) {
if (c == 'U') return 1;
if (c == 'D') return 2;
if (c == 'L') return 3;
return 4;
}
void add(int x, int y, int c, int w) {
e[++cnt] = (Edge) {e[x].next, y, c, w};
e[x].next = cnt;
}
void Add(int x, int y, int c, int w) {
add(x, y, c, w), add(y, x, 0, -w);
}
bool spfa(int s, int t) {
for (int i = 0; i <= t; i++)
dis[i] = INT_MAX, used[i] = 0;
queue <int> q; q.push(s); dis[s] = 0;
while (!q.empty()) {
int x = q.front(); q.pop(); used[x] = 0;
for (int p = e[x].next; p; p = e[p].next) {
int k = e[p].num, c = e[p].c, w = e[p].w;
if (c && dis[k] > dis[x] + w) {
dis[k] = dis[x] + w;
pre[k] = x, las[k] = p;
if (!used[k]) q.push(k), used[k] = 1;
}
}
}
return dis[t] != INT_MAX;
}
int EK(int s, int t) {
int ret = 0;
while (spfa(s, t)) {
int fl = INT_MAX;
for (int x = t; x != s; x = pre[x])
chkmin(fl, e[las[x]].c);
for (int x = t; x != s; x = pre[x])
e[las[x]].c -= fl, e[las[x] ^ 1].c += fl;
ret += fl * dis[t];
}
return ret;
}
int main() {
read(n), read(m);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++) {
char c = getchar();
while (!isalpha(c)) c = getchar();
a[i][j] = num(c);
}
s = 0, t = cnt = 2 * n * m + 1;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++) {
int x = calc(i, j), x1 = x * 2 - 1, x2 = x1 + 1;
Add(s, x1, 1, 0), Add(x2, t, 1, 0);
for (int k = 1; k <= 4; k++) {
int tx = (i + dx[k] - 1 + n) % n + 1, ty = (j + dy[k] - 1 + m) % m + 1;
int y = calc(tx, ty), y2 = y * 2;
Add(x1, y2, 1, (k != a[i][j]));
}
}
cout << EK(s, t) << "\n";
return 0;
}