【UVALive】4043 Ants KM匹配

传送门:【UVALive】4043 Ants


题目分析:裸的最小权匹配。将权值取反进行最大权匹配即可。


代码如下:


#include<cmath>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std ;
  
typedef long long LL ;
  
#define rep( i , a , b ) for ( int i = a ; i < b ; ++ i )
#define For( i , a , b ) for ( int i = a ; i <= b ; ++ i )
#define rev( i , a , b ) for ( int i = a ; i >= b ; -- i )
#define travel( e , H , u ) for ( Edge* e = H[u] ; e ; e = e -> next )
#define clr( a , x ) memset ( a , x , sizeof a )
#define cpy( a , x ) memcpy ( a , x , sizeof a )
  
const int MAXN = 105 ;
const double INF = 1e18 ;
const double eps = 1e-8 ;

struct Point {
	double x , y ;
} p1[MAXN] , p2[MAXN] ;

int visx[MAXN] , visy[MAXN] , Time ;
int Lx[MAXN] , Ly[MAXN] ;
double dx[MAXN] , dy[MAXN] ;
double G[MAXN][MAXN] ;
double slack[MAXN] ;
int n ;

int sgn ( double x ) {
	return ( x > eps ) - ( x < -eps ) ;
}

int find ( int u ) {
	visx[u] = Time ;
	rep ( v , 0 , n ) {
		if ( visy[v] == Time ) continue ;
		double tmp = dx[u] + dy[v] - G[u][v] ;
		if ( !sgn ( tmp ) ) {
			visy[v] = Time ;
			if ( Ly[v] == -1 || find ( Ly[v] ) ) {
				Lx[u] = v ;
				Ly[v] = u ;
				return 1 ;
			}
		} else if ( slack[v] > tmp ) slack[v] = tmp ;
	}
	return 0 ;
}

void KM () {
	rep ( i , 0 , n ) {
		Lx[i] = Ly[i] = -1 ;
		dx[i] = -INF ;
		dy[i] = 0 ;
		rep ( j , 0 , n ) if ( G[i][j] > dx[i] ) dx[i] = G[i][j] ;
	}
	rep ( i , 0 , n ) {
		rep ( j , 0 , n ) slack[j] = INF ;
		while ( 1 ) {
			++ Time ;
			if ( find ( i ) ) break ;
			double d = INF ;
			rep ( j , 0 , n ) if ( visy[j] != Time && d > slack[j] ) d = slack[j] ;
			rep ( j , 0 , n ) if ( visx[j] == Time ) dx[j] -= d ;
			rep ( j , 0 , n ) if ( visy[j] == Time ) dy[j] += d ;
		}
	}
}

double dist ( const Point& a , const Point& b ) {
	double x = a.x - b.x ;
	double y = a.y - b.y ;
	return sqrt ( x * x + y * y ) ;
}

void solve () {
	int res = 0 ;
	rep ( i , 0 , n ) scanf ( "%lf%lf" , &p1[i].x , &p1[i].y ) ;
	rep ( i , 0 , n ) scanf ( "%lf%lf" , &p2[i].x , &p2[i].y ) ;
	rep ( i , 0 , n ) rep ( j , 0 , n ) G[i][j] = - dist ( p1[i] , p2[j] ) ;
	KM () ;
	rep ( i , 0 , n ) printf ( "%d\n" , Lx[i] + 1 ) ;
}

int main () {
	int flag = 0 ;
	while ( ~scanf ( "%d" , &n ) ) {
		if ( flag ) puts ( "" ) ;
		flag = 1 ;
		solve () ;
	}
	return 0 ;
}


你可能感兴趣的:(uvalive)