poj 3565 Ants KM算法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/discreeter/article/details/50283599

题目: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;
}


阅读更多
换一批

没有更多推荐了,返回首页