POJ3565(最大权匹配)

大白351例题23和这题类似。

最大权匹配一定不存在相交。

需要对距离取反。

#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
#define maxn 211
#define INF 111111111
#define left Left
#define eps 1e-10
bool s[maxn], t[maxn];

int n;
struct node {
    double x, y;
}p[maxn];

double dis (double x1, double y1, double x2, double y2) {
    return sqrt ((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
}

double w[maxn][maxn];
double lx[maxn], ly[maxn];
int left[maxn];

bool match (int i) {
    s[i] = 1;
    for (int j = 1; j <= n; j++) if (abs (lx[i]+ly[j]-w[i][j]) <= eps && !t[j]) {
        t[j] = 1;
        if (!left[j] || match (left[j])) {
            left[j] = i;
            return 1;
        }
    }
    return 0;
}

void update () {
   double a = 1<<30;
    for (int i = 1; i <= n; i++) if (s[i])
        for (int j = 1; j <= n; j++) if (!t[j])
            a = min (a, lx[i]+ly[j]-w[i][j]);
    for (int i = 1; i <= n; i++) {
        if (s[i]) lx[i] -= a;
        if (t[i]) ly[i] += a;
    }
}

void km () {
    for (int i = 1; i <= n; i++) {
        left[i] = lx[i] = ly[i] = 0;
        for (int j = 1; j <= n; j++)
            lx[i] = max (lx[i], w[i][j]);
    }
    for (int i = 1; i <= n; i++) {
        for (; ;) {
            for (int j = 1; j <= n; j++) s[j] = t[j] = 0;
            if (match (i))
                break;
            else update ();
        }
    }
}
int ans[maxn];

int main () {
    //freopen ("data.txt", "r", stdin);
    while (scanf ("%d", &n) == 1) {
        for (int i = 1; i <= n; i++) {
            scanf ("%lf%lf", &p[i].x, &p[i].y);
        }
        memset (w, 0, sizeof w);
        for (int j = 1; j <= n; j++) {
            scanf ("%lf%lf", &p[j+n].x, &p[j+n].y);
            for (int i = 1; i <= n; i++) {
                w[i][j] = -1*dis (p[i].x, p[i].y, p[j+n].x, p[j+n].y);
            }
        }
        km ();
        for (int i = 1; i <= n; i++)
            ans[left[i]] = i;
        for (int i = 1; i <= n; i++)
            printf ("%d\n", ans[i]);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值