UVa 10911 Forming Quiz Teams(dfs)

题意:
给定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;
}

你可能感兴趣的:(uva,10911)