Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

可怜的KM啊

Posted by Aidway at 2010-12-02 22:43:05 on Problem 3565 and last updated at 2010-12-02 22:49:03
KM算法可以解决该问题吗???我郁闷了许久了,至今尚未解决,高手帮忙,谢谢!!!
#include <iostream>
#include <cmath>
using namespace std;

const int MAX=110;
int n;
double colonies[MAX][2];
double apple[MAX][2];
int match[MAX];
double lx[MAX],ly[MAX];
int visx[MAX],visy[MAX];
double map[MAX][MAX];

bool Dfs(int u)   
{
	visx[u]=1;
	for (int v=1;v<=n;v++)
	{
		if (!visy[v] && lx[u]+ly[v] == map[u][v])//<1e-10)
		{
			visy[v]=1;
			if (match[v]==0 || Dfs(match[v]))
			{
				match[v]=u;
				return true;
			}
		}
	}
	return false;
}



void BestMatch()   //求最佳匹配:最小权匹配
{
	double sum=0;
	int i,j,k;
	memset(lx,127,sizeof(lx));  //将lx初始化为很大的数,不是127
        memset(ly,0,sizeof(ly));
	/* 此处lx取最小值,因为是求最小权匹配 */ 
	for (i=1;i<=n;i++)
	{
		for (j=1;j<=n;j++) 
		{
			if (map[i][j] < lx[i])
			{
				lx[i]=map[i][j];
			}
		}
	}
	memset(match,0,sizeof(match));
	for (i=1;i<=n;i++)
	{
		while (true)
		{
			memset(visx,0,sizeof(visx));
			memset(visy,0,sizeof(visy));
			double min=10000000000;
			/* 如果找到最佳匹配,及时退出 */
			if (Dfs(i))
			{
				break;
			}
			for (k=1;k<=n;k++)
			{
				if (visx[k])
				{
					for (j=1;j<=n;j++)
					{
											                                if (!visy[j] && map[k][j]-lx[k]-ly[j]<min)
						{
							min=map[k][j]-lx[k]-ly[j];
						}
					}
				}
			}
			/* 修改顶标。 */
			for (j=1;j<=n;j++)
			{
				if (visx[j])
				{
					lx[j]+=min;
				}
				if (visy[j])
				{
					ly[j]-=min;
				}
			}
		}
	}
	for (i=1;i<=n;i++)
	{
		for (j=1;j<=n;j++)
		{
			if (match[j] == i)
			{
				cout<<j<<endl;
				break;
			}
		}
	}
}

void GetDis()
{
	
	memset(map,0,sizeof(map));
	for (int i=1;i<=n;i++)
	{
		for (int j=1;j<=n;j++)
		{
			
			double dx=(colonies[i][0]-apple[j][0])*(colonies[i][0]-apple[j][0]);
			double dy=(colonies[i][1]-apple[j][1])*(colonies[i][1]-apple[j][1]);
		//	cout<<colonies[i][0]<<"  "<<colonies[i][1]<<"  "<<apple[i][0]<<"  "<<apple[i][1]<<endl;
		//	map[i][j]=sqrt(dx+dy); 
			map[i][j]=dx+dy;  //计算的是距离的平方
				
		}
	}
}

int main()
{
	int i,j;
	cin>>n;
	for (i=1;i<=n;i++)
	{
		cin>>colonies[i][0]>>colonies[i][1];
	}
	for (i=1;i<=n;i++)
	{
		cin>>apple[i][0]>>apple[i][1];
	}
	GetDis();
	BestMatch();  
	return 0;
}
 

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator