UVa 10911 Forming Quiz Teams [DP]

#Description
最优配对问题
2n个点,配成n组,使得距离和最短、
#Algorithm
动态规划
##O(n2*2n)方法
dp[s] 表示 已经配对了的集合为s的情况的最小距离和
每次枚举s,i,j
#Code
##O(n2*2n)方法

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <climits>

using  namespace std;
int n;
const int maxn = 20;
struct Node {
    int x, y;
};
Node nodes[maxn];
double d[maxn][maxn];
double dp[1<<maxn];
double dis(Node node1, Node node2) {
  return sqrt((node1.x - node2.x)*(node1.x - node2.x) + (node1.y - node2.y)*(node1.y - node2.y));
}
void solve() {
  memset(d, 0, sizeof(d));
  memset(dp, 0, sizeof(dp));
  n *= 2;
  int e = 1 << n; //全部集合
  for (int i = 0; i < n; i++) {
    string string1;
    cin >> string1 >> nodes[i].x >> nodes[i].y;
  }
  for (int i = 0; i < n; i++)
    for (int j = i + 1; j < n; j++) {
      d[i][j] = dis(nodes[i], nodes[j]);
    }
  for (int i = 1; i < e; i++) {
    dp[i] = INT_MAX;
  }
  for (int s = 0; s < e; s++) { //全部集合
    for (int i = 0; i < n; i++) {
      for (int j = i + 1; j < n; j++) {
        int sij = (1 << i) | (1 << j); //i,j并集
        if (!(s&sij)) { //i, j不在集合中
          dp[s|sij] = min(dp[s|sij], dp[s] + d[i][j]);
        }
      }
    }
  }
  printf("%.2lf\n", dp[e-1]);
}
int main() {
  //freopen("input.txt", "r", stdin);
  for (int i = 1;;i++) {
    scanf("%d\n", &n);
    if (n == 0) break;
    printf("Case %d: ", i);
    solve();
  }
}

猜你喜欢

转载自blog.csdn.net/YYecust/article/details/51896850