[网络流24题] 深海机器人问题
题目链接:戳我
就是普通的最大费用最大流问题,比较特殊的就是边只能取一次,怎么处理?
其实也很简单,就连一个流量为1,费用为收益的相反数的边,再连一个流量inf,费用为0的边即可。
代码如下:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<queue>
#define MAXN 100010
#define S 0
#define T cnt+1
using namespace std;
int n,m,a,b,c,f,t=1,cnt;
int head[MAXN],dis[MAXN],id[20][20],pre_e[MAXN],pre_v[MAXN],done[MAXN];
struct Edge{int nxt,to,dis,cost;}edge[MAXN<<1];
inline void add(int from,int to,int dis,int cost)
{
edge[++t].nxt=head[from],edge[t].to=to,edge[t].dis=dis,edge[t].cost=cost,head[from]=t;
edge[++t].nxt=head[to],edge[t].to=from,edge[t].dis=0,edge[t].cost=-cost,head[to]=t;
}
inline bool spfa()
{
queue<int>q;
memset(dis,0x3f,sizeof(dis));
memset(done,0,sizeof(done));
q.push(S);done[S]=1;dis[S]=0;
while(!q.empty())
{
int u=q.front();q.pop();done[u]=0;
for(int i=head[u];i;i=edge[i].nxt)
{
int v=edge[i].to;
if(edge[i].dis&&dis[u]+edge[i].cost<dis[v])
{
dis[v]=dis[u]+edge[i].cost;
pre_e[v]=i,pre_v[v]=u;
if(!done[v])
q.push(v),done[v]=1;
}
}
}
if(dis[T]>=0x3f3f3f3f) return false;
int flow=0x3f3f3f3f;
for(int i=T;i!=S;i=pre_v[i]) flow=min(flow,edge[pre_e[i]].dis);
for(int i=T;i!=S;i=pre_v[i]) edge[pre_e[i]].dis-=flow,edge[pre_e[i]^1].dis+=flow;
f+=flow;
c+=flow*dis[T];
return true;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("ce.in","r",stdin);
#endif
scanf("%d%d",&a,&b);
scanf("%d%d",&n,&m);
for(int i=0;i<=n;i++)
for(int j=0;j<=m;j++)
id[i][j]=++cnt;//printf("id[%d][%d]=%d\n",i,j,id[i][j]);
for(int i=0;i<=n;i++)
{
for(int j=0;j<m;j++)
{
int cur;
scanf("%d",&cur);
add(id[i][j],id[i][j+1],1,-cur);//printf("[%d,%d] %d %d\n",id[i][j],id[i][j+1],1,cur);
add(id[i][j],id[i][j+1],0x3f3f3f3f,0);
}
}
for(int j=0;j<=m;j++)
{
for(int i=0;i<n;i++)
{
int cur;
scanf("%d",&cur);
add(id[i][j],id[i+1][j],1,-cur);//printf("[%d,%d] %d %d\n",id[i][j],id[i+1][j],1,cur);
add(id[i][j],id[i+1][j],0x3f3f3f3f,0);
}
}
for(int i=1;i<=a;i++)
{
int k,x,y;
scanf("%d%d%d",&k,&x,&y);
add(S,id[x][y],k,0);//printf("[%d,%d] %d %d\n",S,id[x][y],k,0);
}
for(int i=1;i<=b;i++)
{
int k,x,y;
scanf("%d%d%d",&k,&x,&y);
add(id[x][y],T,k,0);//printf("[%d,%d] %d %d\n",id[x][y],T,k,0);
}
while(spfa());
printf("%d\n",-c);
return 0;
}