bzoj3894:文理分科

传送门

二元组建图
一共有四种二元关系,对于同选文和同选理的情况需要新开两个点来计算
代码:

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
#include<cstring>
using namespace std;
void read(int &x) {
	char ch; bool ok;
	for(ok=0,ch=getchar(); !isdigit(ch); ch=getchar()) if(ch=='-') ok=1;
	for(x=0; isdigit(ch); x=x*10+ch-'0',ch=getchar()); if(ok) x=-x;
}
#define rg register
const int maxn=1e5+10,inf=1e9;queue<int>q;
int n,m,s,t,dis[maxn],ans,cnt=1,pre[maxn*4],nxt[maxn*4],h[maxn],v[maxn*4];
int id(int x,int y){return (x-1)*m+y;}
void add(int x,int y,int z)
{
	pre[++cnt]=y,nxt[cnt]=h[x],h[x]=cnt,v[cnt]=z;
	pre[++cnt]=x,nxt[cnt]=h[y],h[y]=cnt,v[cnt]=0;
}
bool bfs()
{
	memset(dis,0,sizeof dis);
	q.push(s),dis[s]=1;
	while(!q.empty())
	{
		int x=q.front();q.pop();
		for(rg int i=h[x];i;i=nxt[i])
			if(!dis[pre[i]]&&v[i])dis[pre[i]]=dis[x]+1,q.push(pre[i]);
	}
	return dis[t];
}
int dfs(int x,int flow)
{
	if(x==t||!flow)return flow;
	int f=flow;
	for(rg int i=h[x];i;i=nxt[i])
		if(dis[pre[i]]>dis[x]&&v[i])
		{
			int y=dfs(pre[i],min(v[i],f));
			f-=y,v[i]-=y,v[i^1]+=y;
			if(!f)return flow;
		}
	if(f==flow)dis[x]=-1;
	return flow-f;
}
int main()
{
	read(n),read(m),s=0,t=n*m*3+1;
	for(rg int i=1,x;i<=n;i++)for(rg int j=1;j<=m;j++)read(x),add(s,id(i,j),x),ans+=x;
	for(rg int i=1,x;i<=n;i++)for(rg int j=1;j<=m;j++)read(x),add(id(i,j),t,x),ans+=x;
	for(rg int i=1,x;i<=n;i++)
		for(rg int j=1;j<=m;j++)
		{
			read(x),add(s,id(i,j)+n*m,x),ans+=x;
			if(i>1)add(id(i,j)+n*m,id(i-1,j),inf);
			if(i<n)add(id(i,j)+n*m,id(i+1,j),inf);
			if(j>1)add(id(i,j)+n*m,id(i,j-1),inf);
			if(j<m)add(id(i,j)+n*m,id(i,j+1),inf);
			add(id(i,j)+n*m,id(i,j),inf);
		}
	for(rg int i=1,x;i<=n;i++)
		for(rg int j=1;j<=m;j++)
		{
			read(x),add(id(i,j)+n*m*2,t,x),ans+=x;
			if(i>1)add(id(i-1,j),id(i,j)+n*m*2,inf);
			if(i<n)add(id(i+1,j),id(i,j)+n*m*2,inf);
			if(j>1)add(id(i,j-1),id(i,j)+n*m*2,inf);
			if(j<m)add(id(i,j+1),id(i,j)+n*m*2,inf);
			add(id(i,j),id(i,j)+n*m*2,inf);
		}
	for(;bfs();ans-=dfs(s,inf));
	printf("%d\n",ans);
}
posted @ 2019-03-31 17:13  蒟蒻--lichenxi  阅读(149)  评论(0编辑  收藏  举报