首页 > 其他分享 >【codevs1227】方格取数2(最大流费最大流-模板

【codevs1227】方格取数2(最大流费最大流-模板

时间:2023-02-08 12:35:20浏览次数:47  
标签:codevs1227 dist int tot 取数 cost incf 流费 id


problem

  • 给出一个n*n的矩阵,每一格有一个非负整数A[i][j],(Aij <= 1000)
  • 现在从(1,1)出发,可以往右或者往下走,最后到达(n,n)
  • 每达到一格,把该格子的数取出来,该格子的数就变成0
  • 这样一共走K次,现在要求K次所达到的方格的数的和最大
  • n<=50, k<=10

solution

  • 把每个格子(i,j)拆成一个“入点”和一个“出点”,整个网格有2*n*n个点。
  • 从每个格子(i,j)的入点连两条有向边到出点,分别表示第一个经过时(容量为1,费用为a[i][j])和后来经过时(容量为k-1,费用为0)。即第一次把数取走,后来不再计算。
  • 从(i,j)的出点到(i+1,j)和(i,j+1)的入点连有向边,容量为k,费用为0。
  • 以(1,1)为源点,(n,n)为汇点,求最大费用最大流。因为格子(i,j)向其他格子转移的时候容量都为k,所以最大流保证了最终会恰好找到k条路线。最大费用就是所求的方格数之和最大值。

codes

#include<iostream>
#include<algorithm>
#include<queue>
#include<cstring>
using namespace std;
const int N = 5050, M = 200010;

//AddEdge
int tot=1, head[N], Next[M], ver[M], cap[M], cost[M];
void AddEdge(int x, int y, int z, int c){
//正向边,初始容量z,单位费用c
ver[++tot] = y, cap[tot] = z, cost[tot] = c;
Next[tot] = head[x], head[x] = tot;
//反向边,初始容量0,单位费用-c,与正向边成对存储
ver[++tot] = x, cap[tot] = 0, cost[tot] = -c;
Next[tot] = head[y], head[y] = tot;
}

//Cost flow
int s, t, incf[N], pre[N];
int dist[N], vis[N];
bool spfa(){
queue<int>q;
memset(dist,0xcf,sizeof(dist));//-inf
memset(vis,0,sizeof(vis));
q.push(s); dist[s]=0; vis[s]=1;
incf[s] = 1<<30; //到s为止的增广路上各边的最小的剩余容量
while(q.size()){
int x = q.front(); q.pop(); vis[x] = 0;
for(int i = head[x]; i; i = Next[i]){
if(!cap[i])continue; //剩余容量为0,不再残量网络中,不遍历
int y = ver[i];
if(dist[y]<dist[x]+cost[i]){//流量都为1,不用乘
dist[y] = dist[x]+cost[i];
incf[y] = min(incf[x], cap[i]);
pre[y] = i;//记录前驱,用于找方案
if(!vis[y])vis[y]=1, q.push(y);
}
}
}
if(dist[t] == 0xcfcfcfcf)return false;//汇点不可达,已求出最大流
return true;
}
int MaxCostMaxflow(){
int flow = 0, cost = 0;
while(spfa()){
int x = t;
while(x != s){
int i = pre[x];
cap[i] -= incf[t];
cap[i^1] += incf[t];//成对存储
x = ver[i^1];
}
flow += incf[t];
cost += dist[t]*incf[t];
}
return cost;
}

//Timu
int n, k;
int id(int i, int j, int k){
return (i-1)*n + j + k*n*n;
}

int main(){
cin>>n>>k;
s = 1, t = 2*n*n;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
int c; cin>>c;
AddEdge(id(i,j,0),id(i,j,1),1,c);
AddEdge(id(i,j,0),id(i,j,1),k-1,0);
if(j < n)AddEdge(id(i,j,1),id(i,j+1,0),k,0);
if(i < n)AddEdge(id(i,j,1),id(i+1,j,0),k,0);
}
}
cout<<MaxCostMaxflow()<<'\n';
return 0;
}


标签:codevs1227,dist,int,tot,取数,cost,incf,流费,id
From: https://blog.51cto.com/gwj1314/6044059

相关文章