4th IIUC Inter-University Programming Contest, 2005 | |
G |
Forming Quiz Teams |
Input: standard input | |
Problemsetter: Sohel Hafiz |
You have been given the job of forming the quiz teams for the next ‘MCA CPCI Quiz Championship’. There are2*N students interested to participate and you have to form N teams, each team consisting of two members. Since the members have to practice together, all the students want their member’s house as near as possible. Let x1 be the distance between the houses of group 1, x2 be the distance between the houses of group 2 and so on. You have to make sure the summation (x1 + x2 + x3 + …. + xn) is minimized.
Input
There will be many cases in the input file. Each case starts with an integer N (N ≤ 8). The next 2*N lines will given the information of the students. Each line starts with the student’s name, followed by the xcoordinate and then the y coordinate. Both x, y are integers in the range 0 to 1000. Students name will consist of lowercase letters only and the length will be at most 20.
Input is terminated by a case where N is equal to 0.
Output
For each case, output the case number followed by the summation of the distances, rounded to 2 decimal places. Follow the sample for exact format.
Sample Input |
Output for Sample Input |
5 |
Case 1: 118.40 |
题意:每两个一组,使得每组的距离的和最小。
思路:典型的状压dp。
AC代码如下:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
int num[20][40100];
double x[20],y[20],dp[140010],dis[20][20];
char s[1010];
int get1(int k)
{ int ans=0;
while(k)
{ if(k&1)
ans++;
k/=2;
}
return ans;
}
int main()
{ int n,i,j,k,p,ret,t=0;
k=1<<16;
for(i=1;i<70000;i++)
dp[i]=1000000000;
for(i=0;i<k;i++)
{ p=get1(i);
if(p%2==0)
{ num[p][0]++;
num[p][num[p][0]]=i;
}
}
while(~scanf("%d",&n) && n)
{ n*=2;
for(i=1;i<=n;i++)
scanf("%s%lf%lf",s,&x[i],&y[i]);
for(i=1;i<70000;i++)
dp[i]=1000000000;
for(i=1;i<=n;i++)
for(j=i+1;j<=n;j++)
{ dis[i][j]=sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]));
dis[j][i]=dis[i][j];
}
for(p=0;p<n;p+=2)
{for(i=1;i<=n;i++)
for(j=i+1;j<=n;j++)
for(k=1;k<=num[p][0];k++)
{ if((num[p][k] & (1<<(i-1)))==0 && (num[p][k] & (1<<(j-1)))==0)
{ ret=num[p][k]+(1<<(i-1))+(1<<(j-1));
dp[ret]=min(dp[ret],dp[num[p][k]]+dis[i][j]);
}
}
}
printf("Case %d: %.2f\n",++t,dp[(1<<n)-1]);
}
}