• HDU2255 奔小康赚大钱 最大权值匹配


    题意:此乃第一道真正意义上的最大权值匹配,其他题目其实都是求一个最小权值匹配。

    代码如下:

    #include <cstdlib>
    #include <cstring>
    #include <cstdio>
    #include <iostream>
    #include <algorithm>
    using namespace std;
    
    const int INF = 0x3f3f3f3f;
    
    int N;
    int w[305][305];
    int lx[305], ly[305];
    int sx[305], sy[305];
    int match[305], slack[305];
    
    int path(int u) {
        sx[u] = 1;
        for (int i = 1; i <= N; ++i) {
            if (sy[i]) continue;
            int t = lx[u] + ly[i] - w[u][i];
            if (!t) {
                sy[i] = 1;
                if (!match[i] || path(match[i])) {
                    match[i] = u;
                    return true;
                }
            } else {
                slack[i] = min(slack[i], t);
            }
        }
        return false;
    }
    
    void KM() {
        memset(match, 0, sizeof (match));
        memset(ly, 0, sizeof (ly));
        memset(lx, 0, sizeof (lx));
        for (int i = 1; i <= N; ++i) {
            for (int j = 1; j <= N; ++j) {
                lx[i] = max(lx[i], w[i][j]);    
            }
        }
        for (int i = 1; i <= N; ++i) {
            memset(slack, 0x3f, sizeof (slack));
            while (1) {
                memset(sx, 0, sizeof (sx));
                memset(sy, 0, sizeof (sy));
                if (path(i)) break;
                int d = INF;
                for (int j = 1; j <= N; ++j) {
                    if (!sy[j]) d = min(d, slack[j]);
                }
                for (int j = 1; j <= N; ++j) {
                    if (sx[j]) lx[j] -= d;
                    if (sy[j]) ly[j] += d;
                    else slack[j] -= d;
                }
            }
        }
        int ret = 0;
        for (int i = 1; i <= N; ++i) {
            ret += w[match[i]][i];    
        }
        printf("%d\n", ret);
    }
    
    int main() {
        while (scanf("%d", &N) != EOF) {
            for (int i = 1; i <= N; ++i) {
                for (int j = 1; j <= N; ++j) {
                    scanf("%d", &w[i][j]);
                }
            }
            KM();
        }
        return 0;    
    }
  • 相关阅读:
    openjudge-NOI 2.6-1996 登山
    openjudge-NOI 2.6-1944 吃糖果
    openjudge-NOI 2.6-1808 公共子序列
    openjudge-NOI 2.6-1775 采药
    openjudge-NOI 2.6-1768 最大子矩阵
    openjudge-NOI 2.6-1759 最长上升子序列
    tyvj P1050 最长公共子序列
    动态规划-最长公共子序列
    动态规划-最长上升子序列
    HDU 1811 Rank of Tetris
  • 原文地址:https://www.cnblogs.com/Lyush/p/3024443.html
Copyright © 2020-2023  润新知