题意:
给定n,有2*n个人,分成两人一组的n组,每个人在一个坐标上,要求出所有组的两人距离的和最小。
解析:直接暴力求解,详见代码。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int INF = 0x3f3f3f3f;
const int N = 20;
struct Point {
double x,y;
}p[N];
int n;
bool vis[N];
char name[30];
double ans;
inline double dis(Point a,Point b) {
return sqrt((a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y));
}
void dfs(int cur,double sum) {
if(cur == n) {
ans = min(ans,sum);
return;
}
if(sum > ans) {
return;
}
int i = cur;
while(vis[i]) {
i++;
}
vis[i] = true;
for(int j = i; j < n*2; j++) {
if(!vis[j]) {
vis[j] = true;
dfs(cur+1, sum + dis(p[i],p[j]));
vis[j] = false;
}
}
vis[i] = false;
}
int main() {
double x,y;
int cas = 1;
while(scanf("%d",&n) != EOF && n) {
for(int i = 0; i < 2*n; i++) {
scanf("%s%lf%lf",name,&x,&y);
p[i].x = x;
p[i].y = y;
}
ans = INF;
memset(vis,0,sizeof(vis));
dfs(0,0);
printf("Case %d: %.2lf\n",cas++,ans);
}
return 0;
}
本文介绍了一种解决给定人数分成最短距离组队的算法。通过直接暴力求解方式,实现对输入数据的处理并输出最优解。
209

被折叠的 条评论
为什么被折叠?



