poj 3565 Ants KM算法

题目:http://poj.org/problem?id=3565

题意:给你n个蚁群和n个苹果树,用两个数表示其坐标,把每个蚁群对应一棵苹果树,且所有的蚁群和其对应的苹果树的连线不能相交。输出每个蚁群对应的苹果树

明显的二分图问题,把蚁群与苹果树之间的距离作为边,求完备匹配的最小权值和。最小权值和必定不会出现相交的边,比如AB, CD交于E, 那么明显AC + BD < AB + CD,另外注意double数据的精度问题

#include <iostream>
#include <string>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cctype>
#include <vector>
#include <cmath>
using namespace std;

const int N = 110;
const double INF = 99999999999.0;
const double eps = 1e-6;
int n, nx, ny;
double s[N][N];
double lx[N], ly[N], slack[N];
bool visx[N], visy[N];
int match[N];
struct node
{
    double x, y;
}s1[N], s2[N];

bool hungary(int v)
{
    visx[v] = true;
    for(int i = 0; i < ny; i++)
    {
        if(visy[i]) continue;
        if(fabs(lx[v] + ly[i] - s[v][i]) < eps)
        {
            visy[i] = true;
            if(match[i] == -1 || hungary(match[i]))
            {
                match[i] = v;
                return true;
            }
        }
        else slack[i] = min(slack[i], lx[v] + ly[i] - s[v][i]);
    }

    return false;
}


void km()
{
    memset(match, -1, sizeof match);
    for(int i = 0; i < n; i++)
        lx[i] = -INF, ly[i] = 0.0;
    for(int i = 0; i < nx; i++)
        for(int j = 0; j < ny; j++)
            lx[i] = max(lx[i], s[i][j]);
    for(int i = 0; i < nx; i++)
    {
        for(int j = 0; j < ny; j++)
            slack[j] = INF;
        while(true)
        {
            memset(visx, 0, sizeof visx);
            memset(visy, 0, sizeof visy);
            if(hungary(i)) break;
            else
            {
                double d = INF;
                for(int j = 0; j < ny; j++)
                    if(!visy[j]) d = min(d, slack[j]);
                for(int j = 0; j < nx; j++)
                    if(visx[j]) lx[j] -= d;
                for(int j = 0; j < ny; j++)
                    if(visy[j]) ly[j] += d;
                    else slack[j] -= d;
            }
        }
    }
}

int main()
{
    while(~ scanf("%d", &n))
    {
        for(int i = 0; i < n; i++)
            scanf("%lf%lf", &s1[i].x, &s1[i].y);
        for(int i = 0; i < n; i++)
            scanf("%lf%lf", &s2[i].x, &s2[i].y);

        for(int i = 0; i < n; i++)
            for(int j = 0; j < n; j++)
                s[i][j] = -sqrt((s2[i].x - s1[j].x) * (s2[i].x - s1[j].x) + (s2[i].y - s1[j].y) * (s2[i].y - s1[j].y));

        nx = n, ny = n;
        km();
        for(int i = 0; i < ny; i++)
            printf("%d\n", match[i] + 1);
    }

    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值