题目链接
题意:题目大意:给出n个蚁群与n个苹果树坐标(任意三点不共线),问能否使得每一个蚁群对应一个苹果树,且蚁群到苹果树的路线不相交。
解题报告:构造一个二分图,求出最大完美匹配。(KM算法)
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 105;
#define Inf 1e9
#define db double
#define eps 1e-10
db w[N][N], Lx[N], Ly[N], slack[N];
int n, line[N];
bool S[N], T[N];struct Point{db x, y;
}a[N], b[N];bool find(int i){S[i]=1;for ( int j=1; j<=n; j++ )if( !T[j] ){if( Lx[i]+Ly[j]-w[i][j]<eps ){T[j]=1;if( (!line[j]) || find(line[j]) ){line[j]=i;return true;}} else slack[j]=min(slack[j],Lx[i]+Ly[j]-w[i][j]);} return false;
}void KM(){for ( int i=1; i<=n; i++ ){line[i]=Ly[i]=0;Lx[i]=-Inf;for ( int j=1; j<=n; j++ ) Lx[i]=max(Lx[i],w[i][j]);}for ( int i=1; i<=n; i++ ){for ( int j=1; j<=n; j++ ) slack[j]=Inf;while( true ){for ( int j=1; j<=n; j++ ) S[j]=T[j]=0;if( find(i) ) break;db d=Inf;for ( int j=1; j<=n; j++ ) if( !T[j] ) d=min(d,slack[j]);for ( int j=1; j<=n; j++ ){if( S[j] ) Lx[j]-=d;if( T[j] ) Ly[j]+=d;} }}
}int main(){int cnt=0;while( ~scanf("%d", &n ) && n ){if( cnt++ ) puts("");memset(line,0,sizeof(line));for ( int i=1; i<=n; i++ ) scanf("%lf%lf", &a[i].x, &a[i].y );for ( int i=1; i<=n; i++ ) scanf("%lf%lf", &b[i].x, &b[i].y );for ( int i=1; i<=n; i++ )for ( int j=1; j<=n; j++ )w[i][j]=-sqrt((b[i].x-a[j].x)*(b[i].x-a[j].x) + (b[i].y-a[j].y)*(b[i].y-a[j].y));KM();for ( int i=1; i<=n; i++ ) printf("%d\n", line[i] );}
}