旅行商问题 状压DP

题目:     给定一个n个顶点组成的带权有向图的距离矩阵d(i,j)(INF 表示没有边)。要求从顶点0出发,经过每个顶点恰好一次后再回到顶点0 问所经过的峨边权重的最小值是多少

5 8
0 1 3
0 3 4
1 2 5
2 0 4
2 3 5
3 4 3
4 1 6
4 0 7

22

状压DP解法:代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
#include<set>
#include<algorithm>
#include<map>
#define maxn 2005
#define inf 1000000007
typedef long long ll;
using namespace std;
int d[maxn][maxn];
int dp[maxn][maxn];
int a,b,c,n,m;
void solve()
{
    for(int s=0;s<1<<n;s++)
    {
        fill(dp[s],dp[s]+n,inf);
    }
    dp[(1<<n)-1][0]=0;
    for(int s=(1<<n)-2;s>=0;s--)
        for(int v=0;v<n;v++)
        for(int u=0;u<n;u++)
    {
        if(!(s>>u&1))
        {
            dp[s][v]=min(dp[s][v],dp[s|1<<u][u]+d[v][u]);
        }
    }
    printf("%d
",dp[0][0]);
}
int main()
{
    cin>>n>>m;
    for(int i=0;i<n;i++)
    fill(d[i],d[i]+n,inf);
    for(int i=0;i<m;i++)
    {
        cin>>a>>b>>c;
        d[a][b]=c;
    }
    solve();
    return 0;
}
原文地址:https://www.cnblogs.com/huangzzz/p/9294225.html