【bzoj3171】[Tjoi2013]循环格 (费用流)

题意:N*M的矩阵,每个格子有一个LRUD标记表示走到这个格子后下一个格子往哪个方向走。走出边界后自动到另一端。问至少修改几个格子使得在任意一个格子上开始都可以最后回到自身。N,M<=15.

这个15真是迷一样的数据范围。。搜的话太大了,DP的话太小了。。然后我就想是不是各种状态很复杂的或者是状压DP,想了差不多15分钟没想出来。。真是太蠢啦!!以前做过一道题是要让一个有向图中每个点处于k个环内,而这道题是让每个格子处于一个环内(因为每个格子只能有一条出边),竟然没有联想到。。处理这种问题的时候其实不是很好确定怎样构造环,但是可以抽象出来,每个格子处于环内等价于每个格子的入度和出度都是1.这样的话每个格子拆成两个点连边跑费用流就行了,每个格子朝上下左右连边,如果本来就是有边那费用就是0,否则费用是1.

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<map>
using namespace std;
#define clr(a) memset(a,0,sizeof a)
#define rep(i,a,b) for(int i=a;i<=b;++i)
#define erp(i,a,b) for(int i=a;i>=b;--i)

const int inf = 0x3f3f3f3f;
const int MAXN = 666;
const int MAXM = 66666;

int dd[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};
char sym[4] = {'U','D','L','R'};

struct Ed { int to, c, w, nxt; };
struct FlowNet
{
	Ed e[MAXM];
	int ec, adj[MAXN], vn, S, T, dis[MAXN];
	int flow, cost;
	bool vis[MAXN];
	void init(int n, int s, int t)
	{
		vn = n, S = s, T = t;
		rep(i, 1, vn) adj[i] = -1;
	}
	void adde(int a, int b, int c, int w)
	{
		e[ec].to = b;
		e[ec].c = c;
		e[ec].w = w;
		e[ec].nxt = adj[a];
		adj[a] = ec++;
		e[ec].to = a;
		e[ec].c = 0;
		e[ec].w = -w;
		e[ec].nxt = adj[b];
		adj[b] = ec++;
	}
	bool update()
	{
		int tmp = inf;
		rep(u, 1, vn) if (vis[u])
			for (int i = adj[u]; ~i; i=e[i].nxt)
				if (!vis[e[i].to] && e[i].c>0)
					tmp = min(tmp, dis[e[i].to]-dis[u]+e[i].w);
		if (tmp == inf) return 0;
		rep(u, 1, vn) if (vis[u]) dis[u] += tmp;
		return 1;
	}
	int aug(int u, int augco)
	{
		if (u == T)
		{
			flow += augco;
			cost += augco * dis[S];
			return augco;
		}
		vis[u] = 1;
		int delta, augc = augco;
		for (int i = adj[u]; augc&&~i; i=e[i].nxt)
		{
			int v = e[i].to;
			if (!vis[v] && e[i].c>0 && dis[u]==dis[v]+e[i].w)
			{
				delta = aug(v, min(e[i].c, augc));
				augc -= delta;
				e[i].c -= delta, e[i^1].c += delta;
			}
		}
		return augco - augc;
	}
	int mcmf()
	{
		flow = cost = 0;
		do {
			do clr(vis); while (aug(S, inf));
		} while (update());
		return cost;
	}
} G;

char s[22][22];
int N, M;
int in[22][22], out[22][22], idn;
int main()
{
	scanf("%d%d", &N, &M);
	rep(i, 1, N) scanf("%s", s[i]+1);
	G.init(N*M*2+2, N*M*2+1, N*M*2+2);
	rep(i, 1, N) rep(j, 1, M) in[i][j]=++idn, out[i][j]=++idn;
	rep(i, 1, N) rep(j, 1, M)
	{
		G.adde(G.S, in[i][j], 1, 0);
		G.adde(out[i][j], G.T, 1, 0);
		int ii, jj, w;
		rep(t, 0, 3)
		{
			ii = i+dd[t][0], jj = j+dd[t][1];
			if (ii==0) ii = N;
			else if (ii==N+1) ii = 1;
			if (jj==0) jj = M;
			else if (jj==M+1) jj = 1;
			w = (s[i][j]!=sym[t]);
			G.adde(in[i][j], out[ii][jj], 1, w);
		}
	}
	printf("%d\n", G.mcmf());
	return 0;
}

你可能感兴趣的:(【bzoj3171】[Tjoi2013]循环格 (费用流))