POJ - 3311 Hie with the Pie (状压dp+最短路)

博客给出题目链接,题目要求是在给定图中求从0点经过所有点再回到0点的最短路径。思路是用状态压缩,将经过点的情况压缩成状态sta,通过动态规划求解,用floyd预处理距离,最后找出经过所有点后从某点回到0的最短路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:http://poj.org/problem?id=3311

题意:给你一个图,求从0点经过所有点再回到0点的最短路径。

思路:1表示经过了这个点,0表示没经过,压缩成状态sta,dp[sta][i]表示现在是sta状态,此时到达点i的最短距离。

那么dp[sta][i]=min( dp[sta][i] , dp[没经过i的状态][j] + dis[j][i] ) j点为中间点,像floyd一样。而dis[i][j]可以floyd预处理出来。

最后答案就是经过所有点后从某点回到0,1~n找一遍就行了。

代码:

 

#include <cstdio>
#include <cmath>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <numeric>
#include <set>
#include <string>
#include <cctype>
#include <sstream>
#define INF 0x3f3f3f3f
#define eps 1e-8
#define fuck(x) cout<<"<"<<x<<">"<<endl
#define fi first
#define se second
#define pb push_back 
#define lson l, m, rt<<1
#define rson m+1, r, rt<<1|1
using namespace std;
typedef long long LL;
typedef unsigned long long ull;
typedef pair<LL, LL> pii;
const double PI = acos(-1.0);
const LL INFLL = 0x3f3f3f3f3f3f3f3fll;
const int maxn = 1e5 + 5;
const int mod = 1e9 + 7;


int n;
int d[15][15];
int dp[3000][15];
int main() {
    while (~scanf ("%d",&n)&&n){
        for (int i=0;i<=n;i++) for (int j=0;j<=n;j++) scanf ("%d",&d[i][j]);
        for (int i=0;i<=n;i++) for (int j=0;j<=n;j++) for (int k=0;k<=n;k++) 
            d[i][j]=min(d[i][j],d[i][k]+d[k][j]);
        memset(dp,INF,sizeof(dp));
        for (int sta=0;sta<(1<<n);sta++){
            for (int i=1;i<=n;i++){
                if (sta&(1<<(i-1))){
                    if (sta==(1<<(i-1))) dp[sta][i]=d[0][i];
                    else {
                        for (int j=1;j<=n;j++){
                            if (i==j) continue;
                            if (sta&(1<<(j-1))) dp[sta][i]=min(dp[sta][i],dp[sta^(1<<(i-1))][j]+d[j][i]);
                        }
                    }
                }
            }
        }
        int ans=INF;
        for (int i=1;i<=n;i++) ans=min(ans,dp[(1<<n)-1][i]+d[i][0]);
        printf ("%d\n",ans);
    }
    return 0;
} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值