4thIIUCInter-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 are 2*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 x 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 Case 2: 1.41 |
解决方案:出两两组合的点构成的线段,找出最短的总和,可用状态压缩,每次在原来的基础上加两个以前从未出现过点点。
dp[(k|(1<<(u)))|(1<<(w))]=min(dp[(k|(1<<(u)))|(1<<(w))],dp[k]+dis(u,w));u,w为新加的两个点,dis为这两个点的距离。
code:
#include <iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
double dp[70000];
const int inf=0x3f3f3f3f;
int cnt(int s)
{
int c=0;
while(s)
{
c+=(s&0x1);
s>>=1;
}
return c;
}
struct node
{
double x,y;
} N[20];
double dis(int u,int w)
{
return sqrt((N[u].x-N[w].x)*(N[u].x-N[w].x)+(N[u].y-N[w].y)*(N[u].y-N[w].y));
}
int main()
{
int n,o=0;
while(~scanf("%d",&n)&&n)
{
char name[40];
getchar();
for(int i=0; i<2*n; i++)
{
scanf("%s %lf %lf",name,&N[i].x,&N[i].y);
}
for(int i=0; i<=1<<(2*n); i++)
dp[i]=inf;
dp[0]=0;
for(int i=2; i<=2*n; i+=2)
{
for(int k=0; k<(1<<(2*n)); k++)
{
if(cnt(k)==i-2)
{
for(int u=0; u<2*n; u++)
{
if(((1<<u)&k)) continue;
for(int w=u; w<2*n; w++)
{
if(((1<<w)&k)) continue;
dp[(k|(1<<(u)))|(1<<(w))]=min(dp[(k|(1<<(u)))|(1<<(w))],dp[k]+dis(u,w));
}
}
}
}
}
printf("Case %d: %.2lf\n",++o,dp[(1<<(2*n))-1]);
}
return 0;
}