[网络流24题] 18 分配问题(二分图最佳匹配,最小费用最大流)

时间:2021-07-07 06:16:45

题目大意:

有n个工作要分配给n个人做,给出每个人做每件工作所产生的效益, 求出最小总效益和最大总效益;

思路分析:

这道题 和17题的思路是一样的;

①:设立一个源点s,从s向每个人连一条边,容量为1, 费用为0;

②:从每个人向每个工作连一条边,容量为INF,费用为这个人做该工作产生的效益;

③:设立一个汇点,从每个工作向汇点连一条边,容量为1,费用为0;

代码实现:

#include<cstdio>
#include<cstring>
#include<queue>
#include<iostream>
#define Min(a,b) ((a)<(b)?(a):(b))
#define Max(a,b) ((a)>(b)?(a):(b))
using namespace std;
const int N=210, M=20410, INF=0x3f3f3f3f;
int n, m, s, t ,top, sum_cost;
int head[N], vis[N], dis[N], minflow[N], pre[N], path[N], cost[110][110];

struct Edge{
    int to, next, flow, cost;
    Edge(int _to=0,int _next=0,int _flow=0,int _cost=0):to(_to),next(_next),flow(_flow),cost(_cost){}
}edge[M];

void Addedge(int from, int to, int flow, int cost){
    edge[top] = Edge(to, head[from], flow, cost);
    head[from] = top++;
    edge[top] = Edge(from, head[to], 0, -cost);
    head[to] = top++;
}

int Spfa(){
    queue<int> q;
    memset(dis, 0x3f, sizeof(dis));
    memset(minflow, 0x3f, sizeof(minflow));
    memset(path, -1, sizeof(path));
    memset(vis, 0, sizeof(vis));
    dis[s]=0; q.push(s);
    while(!q.empty()){
        int u = q.front(); q.pop();
        vis[u] = 0;
        for(int i = head[u]; i + 1; i = edge[i].next){
            if(edge[i].flow && dis[edge[i].to] > dis[u] + edge[i].cost){
                dis[edge[i].to] = dis[u] + edge[i].cost;
                pre[edge[i].to] = u;
                path[edge[i].to] = i;
                minflow[edge[i].to] = Min(minflow[u], edge[i].flow);
                if(!vis[edge[i].to]){
                    vis[edge[i].to] = 1;
                    q.push(edge[i].to);
                }
            }
        }
    }
    if(dis[t] == INF) return 0;
    sum_cost += minflow[t]*dis[t];
    int u = t;
    while(u!=s){
        edge[path[u]].flow -= minflow[t];
        edge[path[u]^1].flow += minflow[t];
        u = pre[u];
    }
    return 1;
}

int main(){
    freopen("job.in", "r", stdin);
    freopen("job.out", "w", stdout);
    scanf("%d", &n);
    memset(head, -1, sizeof(head));
    top = s = sum_cost = 0;
    t = n * 2 + 1;
    int va;
    for(int i = 1; i <= n; ++i){
        Addedge(s, i, 1, 0);
        for(int j = 1; j <= n; ++j){
            scanf("%d", &cost[i][j]);
            Addedge(i, j+n, INF, cost[i][j]);
        }
        Addedge(i+n, t, 1, 0);
    }
    while(Spfa());
    printf("%d\n", sum_cost);
    memset(head, -1, sizeof(head));
    top = s = sum_cost = 0;
    t = n * 2 + 1;
    for(int i = 1; i <= n; ++i){
        Addedge(s, i, 1, 0);
        for(int j = 1; j <= n; ++j) Addedge(i, j+n, INF, -cost[i][j]);
        Addedge(i+n, t, 1, 0);
    }
    while(Spfa());
    printf("%d\n", -sum_cost);
}