UVa 10911 Forming Quiz Teams(状态压缩DP)
题意:
有2*n个点,使其组成n对,求n对点集的最小距离之和。
思路:
由于2*n最大才20,完全可以由数字的位来表示,每一个数字表示一个状态,然后才去记忆化搜索的方式得出结果。
(看了别人的题解才想起来怎么去做,关于状态压缩的动归,还是没能很好的形成思维。多观察,多总结规律然后归纳之,减少冗余,使收益最大化)
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <climits>
#include <algorithm>
#include <cmath>
using namespace std;
const int MAXD = 65600;
const int MAXN = 25;
double map[MAXN][MAXN];
int x[MAXN], y[MAXN], n;
double dp[MAXD];
double solve(int s)
{
if (dp[s] != -1)
return dp[s];
dp[s] = INT_MAX;
for (int i = 0; i < n; ++i)
if (s & (1 << i))
for (int j = 0; j < n; ++j)
if (i != j && (s & (1 << j)))
dp[s] = min(dp[s], solve(s ^ (1 << i) ^ (1 << j)) + map[i][j]);
return dp[s];
}
int main()
{
int cases = 0;
while (scanf("%d", &n) && n)
{
char b[100];
n <<= 1;
for (int i = 0; i < n; ++i)
scanf("%s %d %d", b, &x[i], &y[i]);
for (int i = 0; i < n; ++i)
for (int j = 0; j < i; ++j)
map[i][j] = map[j][i] = sqrt(1.0 * ((x[i]-x[j])*(x[i]-x[j]) + (y[i]-y[j])*(y[i]-y[j])));
int end = (1 << n) - 1;
for (int i = 1; i <= end; ++i)
dp[i] = -1;
dp[0] = 0;
solve(end);
printf("Case %d: %.2f\n", ++cases, dp[end]);
}
return 0;
}
-------------------------------------------------------
kedebug
Department of Computer Science and Engineering,
Shanghai Jiao Tong University
E-mail: kedebug0@gmail.com
GitHub: http://github.com/kedebug
-------------------------------------------------------