题意:有n个物品,要搬回起点,每次出去能搬两个回来,耗时 = 两点距离的平方,求最少耗时。
思路:状压,选一个点更新下(回去),接着再选一个点(拿回这两个)更新。dp[en]就是最后的答案,不过直接这样会超时,这些点哪组先拿都一样,所以只要更新一组的最优情况就进行下一组,上面选第二个点的循环结束后就跳出第一个点的循环。
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<string>
#include<stdlib.h>
#include<math.h>
#include<vector>
#include<list>
#include<map>
#include<stack>
#include<queue>
#include<algorithm>
#include<numeric>
#include<functional>
using namespace std;
typedef long long ll;
const int maxn = (1<<24)+5;
int dp[maxn],pre[maxn],dis[50][50];
struct data
{
int x,y;
}node[50];
void dist(int n)
{
for(int i = 0; i <= n; i++)
{
for(int j = i+1; j <= n; j++)
dis[i][j] = dis[j][i] = (node[i].x-node[j].x)*(node[i].x-node[j].x)+(node[i].y-node[j].y)*(node[i].y-node[j].y);
}
}
void dfs(int s,int n)
{
int a,b;
a = b = -1;
if(s == 0)
return;
int tp = pre[s];
for(int i = 1; i <= n; i++)
{
if((s & 1<<(i-1)) && !(tp & 1<<(i-1)))
{
if(a == -1)
a = i;
else if(b == -1)
b = i;
else
break;
}
}
dfs(tp,n);
printf(" %d",a);
if(b != -1)
printf(" %d",b);
printf(" 0");
}
int main(void)
{
int n,i,j,k;
while(scanf("%d%d",&node[0].x,&node[0].y)!=EOF)
{
scanf("%d",&n);
for(i = 1; i <= n; i++)
scanf("%d%d",&node[i].x,&node[i].y);
dist(n);
memset(dp,0x3f,sizeof dp);
dp[0] = 0;
int en = (1<<n)-1;
for(int s = 1; s <= en; s++)
{
for(i = 1; i <= n; i++)
{
if(s & (1<<(i-1)))
{
if(dp[s & ~(1<<(i-1))] + 2*dis[i][0] < dp[s])
{
dp[s] = dp[s & ~(1<<(i-1))] + 2*dis[i][0];
pre[s] = s & ~(1<<(i-1));
}
for(j = i+1; j <= n; j++)
{
if(s & (1<<(j-1)))
{
if(dp[s & ~(1<<(i-1)) & ~(1<<(j-1))] + dis[i][0] + dis[j][0] + dis[i][j] < dp[s])
{
dp[s] = dp[s & ~(1<<(i-1)) & ~(1<<(j-1))] + dis[i][0] + dis[j][0] + dis[i][j];
pre[s] = s & ~(1<<(i-1)) & ~(1<<(j-1));
}
}
}
break;
}
}
}
printf("%d\n",dp[en]);
putchar('0');
dfs(en,n);
putchar('\n');
}
return 0;
}