bzoj2127: happiness

传送门:http://www.lydsy.com/JudgeOnline/problem.php?id=2127

思路:二元组建图


要求的就是i选A就有A[i]收益,选B就有B[i]收益,j相同,两两之间如果同时选A就有A[i,j]的额外收入,同时选B就有B[i,j]的额外收入

先把收益加起来,在减掉最小损失即可

最小损失就可以用上面的构图,解出方程赋相应的边权求最小割即可


这题除了读入还是很愉快的


#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
const int N=110,maxn=10010,maxm=300010,inf=1061109567;
using namespace std;
int n,m,A[N][N],B[N][N],sum;
int id(int x,int y){return (x-1)*m+y;}

struct Flow{
	int pre[maxm],now[maxn],son[maxm],val[maxm],tot,dis[maxn],S,T,q[maxm+10],head,tail;
	void add(int a,int b,int c){pre[++tot]=now[a],now[a]=tot,son[tot]=b,val[tot]=c;}
	void ins(int a,int b,int c){add(a,b,c),add(b,a,0);}
	void ins2(int a,int b,int c){add(a,b,c),add(b,a,c);}
	void init(){memset(now,0,sizeof(now)),tot=1,S=maxn-2,T=maxn-1;}
	bool bfs(){
		memset(dis,-1,sizeof(dis));
		q[tail=1]=S,dis[S]=head=0;
		while (head!=tail){
			if (++head>maxn) head=1;
			int x=q[head];
			for (int y=now[x];y;y=pre[y])
				if (dis[son[y]]==-1&&val[y]){
					if (++tail>maxn) tail=1;
					dis[son[y]]=dis[x]+1,q[tail]=son[y];
				}
		}
		return dis[T]>0;
	}
	int find(int x,int low){
		if (x==T) return low;
		int y,res=0;
		for (y=now[x];y;y=pre[y]){
			if (dis[son[y]]!=dis[x]+1||!val[y]) continue;
			int tmp=find(son[y],min(low,val[y]));
			res+=tmp,low-=tmp,val[y]-=tmp,val[y^1]+=tmp;
			if (!low) break;
		}
		if (!y) dis[x]=-1;
		return res;
	}
	void build(){
		int v;
		for (int i=1;i<n;i++) for (int j=1;j<=m;j++){
			scanf("%d",&v);
			A[i][j]+=v,A[i+1][j]+=v,sum+=v;
			ins2(id(i,j),id(i+1,j),v);
		}
		//printf("%d\n",sum);
		for (int i=1;i<n;i++) for (int j=1;j<=m;j++){
			scanf("%d",&v);
			B[i][j]+=v,B[i+1][j]+=v,sum+=v;
			ins2(id(i,j),id(i+1,j),v);
		}
		//printf("%d\n",sum);
		for (int i=1;i<=n;i++) for (int j=1;j<m;j++){
			scanf("%d",&v);
			A[i][j]+=v,A[i][j+1]+=v,sum+=v;
			ins2(id(i,j),id(i,j+1),v);
		}
		//printf("%d\n",sum);
		for (int i=1;i<=n;i++) for (int j=1;j<m;j++){
			scanf("%d",&v);
			B[i][j]+=v,B[i][j+1]+=v,sum+=v;
			ins2(id(i,j),id(i,j+1),v);
		}
		//printf("%d\n",sum);
		for (int i=1;i<=n;i++) for (int j=1;j<=m;j++) ins(S,id(i,j),A[i][j]),ins(id(i,j),T,B[i][j]);
	}
	void work(){
		int res=0;
		while (bfs()) res+=find(S,inf);
		printf("%d\n",sum-(res>>1));
	}
}F;

int main(){
	scanf("%d%d",&n,&m),F.init();
	for (int i=1;i<=n;i++) for (int j=1;j<=m;j++) scanf("%d",&A[i][j]),sum+=A[i][j],A[i][j]<<=1;
	for (int i=1;i<=n;i++) for (int j=1;j<=m;j++) scanf("%d",&B[i][j]),sum+=B[i][j],B[i][j]<<=1;
	//printf("%d\n",sum);
	F.build(),F.work();//printf("%d\n",sum);
	return 0;
}



posted @ 2016-01-21 10:57  orzpps  阅读(133)  评论(0编辑  收藏  举报