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*Nlines will given the information of the students. Each line starts with the student’s name, followed by thex coordinate 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 |
LRJ小白书上讲过的类似两两配对问题,状压dp。
dp(s)=max(dp(s-{i}-{j})+dis(i,j)} ,i为s里最高位的1,j为s里不同于i的1.
代码:
#include<cstdio>
#include<cmath>
#include<iostream>
using namespace std;
char s[30];
int x[20],y[20];
double dp[1<<16];
const int inf=1<<30;
double dis(int a,int b){
return sqrt((x[a]-x[b])*(x[a]-x[b])+(y[a]-y[b])*(y[a]-y[b]));
}
int main()
{
int n,i,j,cas=1;
while(scanf("%d",&n),n){
n*=2;
for(i=0;i<n;i++)
scanf("%s%d%d",s,x+i,y+i);
for(i=1;i<(1<<n);i++) dp[i]=inf;
for(int s=0;s<(1<<n);s++){
for(i=n-1;i>=0;i--)
if(s&1<<i) break;
for(j=0;j<i;j++)
if(s&1<<j&&dis(i,j)+dp[s^1<<i^1<<j]<dp[s])
dp[s]=dis(i,j)+dp[s^1<<i^1<<j];
}
printf("Case %d: %.2f\n",cas++,dp[(1<<n)-1]);
}
return 0;
}