【网络流24题】【LOJ6224】深海机器人问题(最大费用最大流)

problem

  • 给定一个n*m的网格,每条边上有一个权值
  • 给定每个机器人的出发位置和目标位置
  • 求权值最大

solution

  • 拆边,每条边拆成2条,第一条容量1,费用c[i],第二条容量inf,费用0;
  • 建超级源汇(s到每个出发位置容量1,费用0,每个目标位置到t容量1,费用0),跑最大费用最大流即可

最后,输入有点毒。。。

codes

#include<iostream>
#include<algorithm>
#include<queue>
#include<cstring>
using namespace std;

const int N = 1100, M = 100010, inf = 1<<30;

//Grape
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 a, b, n, m, mp[N][N];
void input(){
    cin>>a>>b;
    cin>>n>>m;
    s = 0, t = (n+1)*(m+1)+1;
    int cnt = 0;
    for(int i = 0; i <= n; i++)
        for(int j = 0; j <= m; j++)
            mp[i][j] = ++cnt;
    for(int i = 0; i <= n; i++){
        for(int j = 0; j < m; j++){
            int x;  cin>>x;
            AddEdge(mp[i][j],mp[i][j+1],1,x);
            AddEdge(mp[i][j],mp[i][j+1],inf,0);
        }
    }
    for(int j = 0; j <= m; j++){
        for(int i = 0; i < n; i++){
            int x;  cin>>x;
            AddEdge(mp[i][j],mp[i+1][j],1,x);
            AddEdge(mp[i][j],mp[i+1][j],inf,0);
        }
    }
    for(int i = 0; i < a; i++){
        int x, y, z;  cin>>z>>x>>y;
        AddEdge(s,mp[x][y],z,0);
    }
    for(int i = 0; i < b; i++){
        int x, y, z;  cin>>z>>x>>y;
        AddEdge(mp[x][y],t,z,0);
    }
    return ;
}


int main(){
    ios::sync_with_stdio(false);
    input();
    cout<<MaxCostMaxflow()<<'\n';
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_33957603/article/details/80671241
今日推荐