luogu3159 [CQOI2012]交换棋子

把每个点拆成 x y z
对于第 i 个点,x->y是表示流入的,y->z是表示流出的。

#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
int n, m, ss, tt, hea[1305], cnt, minCost, pre[1305], dis[1305], maxFlow, qaq, qwq;
const int oo=0x3f3f3f3f;
const int dx[]={0, 1, 1, 1, 0, -1, -1, -1, 0};
const int dy[]={0, 1, 0, -1, -1, -1, 0, 1, 1};
bool vis[1305];
char cs[25][25], js[25][25], xz[25][25];
struct Edge{
	int too, nxt, val, cst;
}edge[9005];
queue<int> d;
int x(int i, int j){
	return (i-1)*m+j;
}
int y(int i, int j){
	return (i-1)*m+j+n*m;
}
int z(int i, int j){
	return (i-1)*m+j+2*n*m;
}
void add_edge(int fro, int too, int val, int cst){
	edge[cnt].nxt = hea[fro];
	edge[cnt].too = too;
	edge[cnt].val = val;;
	edge[cnt].cst = cst;
	hea[fro] = cnt++;
}
void addEdge(int fro, int too, int val, int cst){
	add_edge(fro, too, val, cst);
	add_edge(too, fro, 0, -cst);
}
int bfs(){
	memset(dis, 0x3f, sizeof(dis));
	memset(pre, -1, sizeof(pre));
	dis[ss] = 0;
	vis[ss] = true;
	d.push(ss);
	while(!d.empty()){
		int x=d.front();
		d.pop();
		vis[x] = false;
		for(int i=hea[x]; i!=-1; i=edge[i].nxt){
			int t=edge[i].too;
			if(dis[t]>dis[x]+edge[i].cst && edge[i].val>0){
				dis[t] = dis[x] + edge[i].cst;
				pre[t] = i;
				if(!vis[t]){
					vis[t] = true;
					d.push(t);
				}
			}
		}
	}
	return dis[tt]!=oo;
}
void dinic(){
	while(bfs()){
		int tmp=oo;
		for(int i=pre[tt]; i!=-1; i=pre[edge[i^1].too])
			tmp = min(tmp, edge[i].val);
		for(int i=pre[tt]; i!=-1; i=pre[edge[i^1].too]){
			edge[i].val -= tmp;
			edge[i^1].val += tmp;
			minCost += tmp * edge[i].cst;
		}
		maxFlow += tmp;
	}
}
int main(){
	memset(hea, -1, sizeof(hea));
	cin>>n>>m;
	for(int i=1; i<=n; i++)	scanf("%s", cs[i]+1);
	for(int i=1; i<=n; i++)	scanf("%s", js[i]+1);
	for(int i=1; i<=n; i++)	scanf("%s", xz[i]+1);
	ss = 0; tt = n * m * 3 + 1;
	for(int i=1; i<=n; i++)
		for(int j=1; j<=m; j++){
			if(cs[i][j]=='1' && js[i][j]=='0'){
				qaq++;
				addEdge(ss, y(i,j), 1, 0);
				addEdge(x(i,j), y(i,j), (xz[i][j]-'0')/2, 0);
				addEdge(y(i,j), z(i,j), (xz[i][j]-'0'+1)/2, 0);//原来黑而后来白,给流出的分多一点容量比较好
			}
			else if(cs[i][j]=='0' && js[i][j]=='1'){
				qwq++;
				addEdge(y(i,j), tt, 1, 0);
				addEdge(x(i,j), y(i,j), (xz[i][j]-'0'+1)/2, 0);
				addEdge(y(i,j), z(i,j), (xz[i][j]-'0')/2, 0);
			}
			else{
				addEdge(x(i,j), y(i,j), (xz[i][j]-'0')/2, 0);
				addEdge(y(i,j), z(i,j), (xz[i][j]-'0')/2, 0);
			}
			for(int k=1; k<=8; k++){
				int kx=i+dx[k];
				int ky=j+dy[k];
				if(kx<1 || kx>n || ky<1 || ky>m)	continue;
				addEdge(z(i,j), x(kx,ky), oo, 1);
			}
		}
	dinic();
	if(qaq==qwq && maxFlow==qwq)	cout<<minCost<<endl;
	else	cout<<"-1"<<endl;
	return 0;
}
posted @ 2018-01-15 11:04  poorpool  阅读(132)  评论(0编辑  收藏  举报