codeforces 8C. Looking for Order 状压dp

时间:2021-03-11 02:18:25

题目链接

给n个物品的坐标, 和一个包裹的位置, 包裹不能移动。 每次最多可以拿两个物品, 然后将它们放到包里, 求将所有物品放到包里所需走的最小路程。

直接状压dp就好了。

#include <iostream>
#include <vector>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <map>
#include <set>
#include <string>
#include <queue>
#include <stack>
#include <bitset>
using namespace std;
#define pb(x) push_back(x)
#define ll long long
#define mk(x, y) make_pair(x, y)
#define lson l, m, rt<<1
#define mem(a) memset(a, 0, sizeof(a))
#define rson m+1, r, rt<<1|1
#define mem1(a) memset(a, -1, sizeof(a))
#define mem2(a) memset(a, 0x3f, sizeof(a))
#define rep(i, n, a) for(int i = a; i<n; i++)
#define fi first
#define se second
typedef pair<int, int> pll;
const double PI = acos(-1.0);
const double eps = 1e-;
const int mod = 1e9+;
const int inf = ;
const int dir[][] = { {-, }, {, }, {, -}, {, } };
int n;
int dp[<<], dis[][], b[<<], ans[], cnt;
pll a[];
int main()
{
int x, y;
cin>>a[].fi>>a[].se;
cin>>n;
a[n] = a[];
for(int i = ; i<n; i++) {
scanf("%d%d", &a[i].fi, &a[i].se);
}
for(int i = ; i<=n; i++) {
for(int j = ; j<=n; j++) {
dis[i][j] = (a[i].fi-a[j].fi)*(a[i].fi-a[j].fi)+(a[i].se-a[j].se)*(a[i].se-a[j].se);
}
}
mem2(dp);
dp[] = ;
for(int i = ; i<(<<n); i++) {
if(dp[i]==inf)
continue;
for(int j = ; j<n; j++) {
if((<<j&i)==) {
for(int k = j; k<n; k++) {
if((<<k&i)==) {
int tmp = i|(<<j)|(<<k);
int d = dis[j][k]+dis[n][j]+dis[n][k];
if(dp[tmp]>dp[i]+d) {
dp[tmp] = dp[i]+d;
b[tmp] = i;
}
}
}
break;
}
}
}
cout<<dp[(<<n)-]<<endl;
for(int i = (<<n)-; i!=; i = b[i]) {
int tmp = b[i]^i;
ans[cnt++] = ;
for(int j = ; j<n; j++) {
if((<<j)&tmp) {
ans[cnt++] = j+;
}
}
}
ans[cnt++] = ;
for(int i = cnt-; i>=; i--) {
printf("%d ", ans[i]);
}
return ;
}