996D 最短Hamilton路径 状压dp

https://ac.nowcoder.com/acm/contest/996/D
状压dp

#include <bits/stdc++.h>
#define ll long long

using namespace std;
const ll inf = 0x3f3f3f;
ll dp[1<<20][21];
ll mp[21][21];
ll n;
int main()
{
    
    
    while(~scanf("%lld",&n))
    {
    
    
        for(int i = 0;i < n;i++)
        {
    
    
            for(int j = 0;j < n;j++)
            {
    
    
                scanf("%lld", &mp[i][j]);
            }
        }
        memset(dp, inf, sizeof(dp));
        dp[1][0] = 0;
        for(int i = 1;i < 1<<n;i++)
        {
    
    
            for(int j = 0;j < n;j++)
                if((i >> j) & 1)
                    for (int k = 0; k < n;k++)
                    {
    
    
                        if(i^(1<<j) >> k & 1)
                        {
    
    
                            dp[i][j] = min(dp[i][j], dp[i ^ (1 << j)][k] + mp[k][j]);
                        }
                    }
        }
        //if(dp[(1<<n)-1][n-1] != inf)
            printf("%lld\n", dp[(1 << n) - 1][n - 1]);

    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42937838/article/details/109957628
今日推荐