当前位置: 代码迷 >> 综合 >> LightOJ - 1071 Baker Vai(最大费用最大流+拆点)
  详细解决方案

LightOJ - 1071 Baker Vai(最大费用最大流+拆点)

热度:63   发布时间:2024-01-24 17:03:32.0

题目链接:点击查看

题目大意:给出一个n*m的矩阵,每个点都有一个权值,现在问要从点(1,1)到点(n,m),每次只能向下或向右走,到达点(n,m)后再回到点(1,1),这次每次只能向上或向左走,除了点(1,1)和点(n,m)外的每个点都只能经过一次,现在问如何规划路线能使得途径权值和最大

题目分析:读完题后感觉和之前做过的K取格子数以及求最短路的一个题结合起来的一样,首先因为每个点只能经过一次,那么我们不妨直接拆点限流,将点权放到边权上,这样就解决了每个点只能经过一次的问题,这里需要注意一下,因为起点和终点可以经过两次,所以记得对这两个点再多加一条流量为1,花费为0的边,如此之后因为相当于需要求一个不想交的回路,我们不妨视为从起点到终点的两条不想交的路径,这样一来就比较好建图了:

  1. 源点->点(1,1)的入点,流量为2,花费为0
  2. 每个点的入点->每个点的出点,流量为1,花费为点权
  3. 点(1,1)的入点->点(1,1)的出点,流量为1,花费为0
  4. 点(n,m)的入点->点(n,m)的出点,流量为1,花费为0
  5. 每个点的出点->向下的点的入点,流量为无穷大,花费为0
  6. 每个点的出点->向右的点的入点,流量为无穷大,花费为0
  7. 点(n,m)的出点->汇点,流量为2,花费为0

建好图后直接跑最大费用最大流的模板就是答案了,补充一下,别看着建图过程比较吓人,其实理解了之后也就是那么一回事

代码:

#include<iostream>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<climits>
#include<cmath>
#include<cctype>
#include<stack>
#include<queue>
#include<list>
#include<vector>
#include<set>
#include<map>
#include<sstream>
using namespace std;typedef long long LL;const int inf=0x3f3f3f3f;const int N=2e4+100;//点const int M=1e5+100;//边struct Edge
{int to,w,cost,next;
}edge[M];int head[N],cnt,n,m;void addedge(int u,int v,int w,int cost)
{edge[cnt].to=v;edge[cnt].w=w;edge[cnt].cost=cost;edge[cnt].next=head[u];head[u]=cnt++;edge[cnt].to=u;edge[cnt].w=0;edge[cnt].cost=-cost;edge[cnt].next=head[v];head[v]=cnt++;
}int d[N],incf[N],pre[N];bool vis[N];bool spfa(int s,int t)
{memset(d,0xcf,sizeof(d));memset(vis,false,sizeof(vis));memset(pre,-1,sizeof(pre));queue<int>q;q.push(s);vis[s]=true;incf[s]=inf;d[s]=0;while(!q.empty()){int u=q.front();q.pop();vis[u]=false;for(int i=head[u];i!=-1;i=edge[i].next){int v=edge[i].to;int w=edge[i].w;int cost=edge[i].cost;if(!w)continue;if(d[v]<d[u]+cost){d[v]=d[u]+cost;pre[v]=i;incf[v]=min(incf[u],w);if(!vis[v]){vis[v]=true;q.push(v);}}}}return pre[t]!=-1;
}int update(int s,int t)
{int x=t;while(x!=s){int i=pre[x];edge[i].w-=incf[t];edge[i^1].w+=incf[t];x=edge[i^1].to;}return d[t]*incf[t];
}void init()
{memset(head,-1,sizeof(head));cnt=0;
}int solve(int st,int ed)
{int ans=0;while(spfa(st,ed))ans+=update(st,ed);return ans;
}int get_id(int x,int y,int k)
{return (x-1)*m+y+k*n*m;
}int main()
{
//  freopen("input.txt","r",stdin);
//  ios::sync_with_stdio(false);int w;cin>>w;int kase=0;while(w--){init();scanf("%d%d",&n,&m);for(int i=1;i<=n;i++){for(int j=1;j<=m;j++){int num;scanf("%d",&num);addedge(get_id(i,j,0),get_id(i,j,1),1,num);if(j<m)addedge(get_id(i,j,1),get_id(i,j+1,0),inf,0);if(i<n)addedge(get_id(i,j,1),get_id(i+1,j,0),inf,0);}}int st=N-1,ed=st-1;addedge(get_id(1,1,0),get_id(1,1,1),1,0);addedge(get_id(n,m,0),get_id(n,m,1),1,0);addedge(st,get_id(1,1,0),2,0);addedge(get_id(n,m,1),ed,2,0);printf("Case %d: %d\n",++kase,solve(st,ed));}return 0;
}

 

  相关解决方案