3171: [Tjoi2013]循环格
dinic跑费用流 先拆点设为X1,X2
建图是 0 -> 任意点的原点X1 花费为0
拆出来的点X2 -> 2nm+1 花费为0
X1指向周围能到的点 花费为0 不能到的点花费为1
BZOJ 3171
/**************************************************************
Problem: 3171
User: Dream_Tonight
Language: C++
Result: Accepted
Time:40 ms
Memory:5600 kb
****************************************************************/
#include <algorithm>
#include <iostream>
#include <cstring>
#include <vector>
#include <string>
#include <cstdio>
#include <cmath>
#include <stack>
#include <queue>
#include <list>
#include <map>
#include <set>
using namespace std;
#define lson l , m , rt << 1
#define rson m + 1 , r , rt << 1 | 1
typedef long long ll;
typedef pair<int, int> pii;
const int maxn = 1e5 + 7;
const int inf = 2139062143;
int n, m, s, t, cnt = 1, result = 0;
char mp[105][105];
int dis[maxn], head[maxn], vis[maxn];
struct node {
int to, next, cap, cost;
} edge[maxn * 2];
void ins(int u, int v, int cap, int cost) {
edge[++cnt] = (node) {v, head[u], cap, cost}, head[u] = cnt;
edge[++cnt] = (node) {u, head[v], 0, -cost}, head[v] = cnt;
}
int bfs() {
queue<int> q;
memset(vis, 0, sizeof(vis));
memset(dis, 127, sizeof(dis));
q.push(t), vis[t] = 1, dis[t] = 0;
while (!q.empty()) {
int u = q.front();
q.pop();
vis[u] = 0;
for (int i = head[u]; i; i = edge[i].next) {
int to = edge[i].to;
if (edge[i ^ 1].cap && dis[to] > dis[u] + edge[i ^ 1].cost) {
dis[to] = dis[u] + edge[i ^ 1].cost;
if (!vis[to]) q.push(to), vis[to] = 1;
}
}
}
return dis[s] != inf;
}
int dfs(int x, int limit) {
if (x == t) return limit;
int flow = 0;
vis[x] = 1;
for (int i = head[x]; i; i = edge[i].next) {
if (edge[i].cap && !vis[edge[i].to] &&
dis[x] + edge[i ^ 1].cost == dis[edge[i].to]) {
if (int d = dfs(edge[i].to, min(edge[i].cap, limit))) {
limit -= d, flow += d;
edge[i].cap -= d, edge[i ^ 1].cap += d;
result += d * edge[i].cost;
if (!limit) break;
}
}
}
return flow;
}
void dinic() {
int ret = 0;
while (bfs()) {
vis[t] = 1;
while (vis[t]) {
memset(vis, 0, sizeof(vis));
ret += dfs(s, inf);
}
}
// cout << ret << endl;
}
int dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};
void build() {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
ins(s, (i - 1) * m + j, 1, 0);
ins((i - 1) * m + j + n * m, t, 1, 0);
int way = 0;
if (mp[i][j] == 'R') way = 2;
if (mp[i][j] == 'L') way = 3;
if (mp[i][j] == 'U') way = 1;
if (mp[i][j] == 'D') way = 0;
for (int k = 0; k < 4; k++) {
int dx = i + dir[k][0];
int dy = j + dir[k][1];
if (dx == 0) dx = n;
if (dx == n + 1)dx = 1;
if (dy == 0) dy = m;
if (dy == m + 1) dy = 1;
if (k == way) ins((i - 1) * m + j, (dx - 1) * m + dy + n * m, 1, 0);
else ins((i - 1) * m + j, (dx - 1) * m + dy + n * m, 1, 1);
}
}
}
}
int main() {
#ifndef ONLINE_JUDGE
freopen("weather.in", "r", stdin);
#endif
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
scanf(" %c", &mp[i][j]);
}
}
s = 0, t = 2 * n * m + 1;
build(), dinic();
printf("%d\n", result);
return 0;
}