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 |
状态压缩dp,貌似记忆化搜索比直接dp要快一点的样子,dp用时0.132ms,记忆化搜索只用了0.032ms。
f[x]=min(f[x^(1<<i)^(1<<j)]) (i为x中最后的1,j为除了i以外的一个1)
-----------------------------
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> using namespace std; const double OO=1e17; struct STU{ int x; int y; }stu[32]; double a[32][32]; int n; char s[111]; double f[1<<17]; bool v[1<<17]; int lowbit(int x) { return x&(-x); } double dfs(int x) { int i,j; double ret=OO; if (v[x]) return f[x]; for (i=0;i<n;i++) { if (x&(1<<i)) break; } for (j=i+1;j<n;j++) { if (x&(1<<j)) { ret=min( ret, dfs(x^(1<<i)^(1<<j))+a[i][j] ); } } f[x]=ret; v[x]=true; return ret; } void DP() { int i,j,x; for (i=0;i<(1<<n);i++) f[i]=OO; f[0]=0; for (x=1;x<(1<<n);x++) { for (i=0;i<n;i++) { if (x&(1<<i)) break; } for (j=i+1;j<n;j++) { if (x&(1<<j)) { f[x]=min( f[x], f[x^(1<<i)^(1<<j)]+a[i][j] ); } } } printf("%0.2lf\n",f[(1<<n)-1]); } int main() { int cnt=1; while (~scanf("%d",&n)) { if (n==0) break; memset(f,0,sizeof(f)); memset(v,0,sizeof(v)); n*=2; for (int i=0;i<n;i++) { scanf("%s%d%d",s,&stu[i].x,&stu[i].y); } for (int i=0;i<n;i++) { for (int j=0;j<n;j++) { a[i][j]=sqrt((stu[i].x-stu[j].x)*(stu[i].x-stu[j].x)+(stu[i].y-stu[j].y)*(stu[i].y-stu[j].y)); } } printf("Case %d: ",cnt++); //DP(); v[0]=true; double ans=dfs((1<<n)-1); printf("%0.2lf\n",ans); } return 0; }