POJ 3311 Hie with the Pie //状态压缩DP

TSP,可以用状态压缩做,记得先用FLOYED处理


#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
int n;
int map[12][12];
int dp[(1 << 11) - 1][11];
int main()
{
    while(scanf("%d", &n) != EOF)
    {
        if(n == 0)  break;
        for(int i = 0; i <= n; i++)
            for(int j = 0; j <= n; j++)
                scanf("%d", &map[i][j]);

        for(int k = 0; k <= n; k++)
            for(int i = 0; i <= n; i++)
                for(int j = 0; j <= n; j++)
                    if(map[i][j] > map[i][k] + map[k][j])
                        map[i][j] = map[i][k] + map[k][j];

        if(n == 1)
        {
            printf("0\n");
            continue;
        }

        /*for(int i = 0; i <= n; i++)
        {
            for(int j = 0; j <= n; j++)
                printf("%d  ", map[i][j]);
            printf("\n");
        }*/

        int rmax = 1 << 30;
        n += 1;
        int N = (1 << n) - 1;

        for(int i = 0; i <= N; i++)
            for(int j = 0; j <= n; j++) dp[i][j] = 100000000;

        dp[1][0] = 0;

        for(int i = 1; i <= N; i++)
        {
            int temp = i;
            int id = 0;
            while(temp)
            {
                if(temp & 1)
                {
                    for(int k = 0; k < n; k++)
                    {
                        dp[i | (1 << k)][k] = min(dp[i | (1 << k)][k], dp[i][id] + map[id][k]);
                        if((i | (1 << k)) == N)
                        {
                            if(dp[i][id] + map[id][k] + map[k][0] < rmax)
                            {
                                rmax = dp[i][id] + map[id][k] + map[k][0];
                            }
                        }
                    }
                }
                id++;
                temp >>= 1;
            }
        }

        /*for(int i = 1; i <= N; i++)
        {
            for(int j = 0; i< n; i++)
            {
                printf("%d  ", dp[i]);
            }
            puts("");
        }*/

        printf("%d\n", rmax);
    }
    return 0;
}


你可能感兴趣的:(POJ 3311 Hie with the Pie //状态压缩DP)