uva10746

题目链接请戳 这里

 

解题思路

带权二分图的最优匹配

注意精度问题

 

代码

#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;

const int maxn = 110;
const int maxm = 5010;
const double INF = 1e16;

struct Edge {
    int from, to, cap, flow;
    double cost;
    Edge(int u, int v, int c, int f, double w):from(u), to(v), cap(c), flow(f), cost(w) {}
};

//这里用的是lrj紫书里的模板 
struct MCMF {
    int n, m;
    vector<Edge> edges;
    vector<int> G[maxn];
    int inq[maxn];
    double d[maxn];
    int p[maxn];
    int a[maxn];
    
    void init(int n)
    {
        this->n = n;
        for (int i = 0; i < n; i++) G[i].clear();
        edges.clear();
    }
    
    void AddEdge(int from, int to, int cap, double cost) {
        edges.push_back(Edge(from, to, cap, 0, cost));
        edges.push_back(Edge(to, from, 0, 0, -cost));
        m = edges.size();
        G[from].push_back(m - 2);
        G[to].push_back(m - 1);
    }
    
    bool BellmanFord(int s, int t, int &flow, double &cost) {
        for (int i = 0; i <= n; i++) d[i] = INF;
        memset(inq, 0, sizeof(inq));
        d[s] = 0; inq[s] = 1; p[s] = -1; a[s] = 1000000000;
        
        queue<int> Q;
        Q.push(s);
        while (!Q.empty()) {
            int u = Q.front(); Q.pop();
            inq[u] = 0;
            for (int i = 0; i < G[u].size(); i++) {
                Edge &e = edges[G[u][i]];
                if (e.cap > e.flow && d[e.to] > d[u] + e.cost) {
                    d[e.to] = d[u] + e.cost;
                    p[e.to] = G[u][i];
                    a[e.to] = min(a[u], e.cap - e.flow);
                    if (!inq[e.to]) { Q.push(e.to); inq[e.to] = 1; }
                }
            }
        }
        if (d[t] == INF) return false;
        flow += a[t];
        cost += d[t] * a[t];
        for (int u = t; u != s; u = edges[p[u]].from) {
            edges[p[u]].flow += a[t];
            edges[p[u] ^ 1].flow -= a[t];
        }
        return true;
    }
    
    int MincostMaxflow(int s, int t, double &cost) {
        int flow = 0; cost = 0;
        while (BellmanFord(s, t, flow, cost));
        return flow;
    }
};

int from[maxm], to[maxm];
long long w[maxm];

int main()
{
    int n, m;
    MCMF A;
    scanf("%d%d", &n, &m); 
    while (!(n == 0 && m == 0)) {
        A.init(n + m + 1);
        for (int i = 1; i <= n; i++) 
            for (int j = 1; j <= m; j++) {
                double weight;
                scanf("%lf", &weight);
                A.AddEdge(n + j, i, 1, weight);
            }
        double cost = 0;
        //超级源点到各个警察有一条容量为1的边
        for (int i = n + 1; i <= n + m; i++)
            A.AddEdge(0, i, 1, 0);
        //各个银行到超级汇点有一条容量为1的边
        for (int i = 1; i <= n; i++)
            A.AddEdge(i, n + m + 1, 1, 0);
        int f = A.MincostMaxflow(0, n + m + 1, cost);
        //可以加一个很小的数来避免精度问题
        printf("%.2lf\n", cost / n + 1e-9);
        scanf("%d%d", &n, &m);
    }
    return 0;
}

 

posted @ 2016-12-09 13:45  啊嘞  阅读(222)  评论(0编辑  收藏  举报