poj3311 状压DP

来源:互联网 发布:电脑软件网站 编辑:程序博客网 时间:2024/06/06 20:56
Hie with the Pie
Time Limit: 2000MS Memory Limit: 65536KTotal Submissions: 6941 Accepted: 3731

Description

The Pizazz Pizzeria prides itself in delivering pizzas to its customers as fast as possible. Unfortunately, due to cutbacks, they can afford to hire only one driver to do the deliveries. He will wait for 1 or more (up to 10) orders to be processed before he starts any deliveries. Needless to say, he would like to take the shortest route in delivering these goodies and returning to the pizzeria, even if it means passing the same location(s) or the pizzeria more than once on the way. He has commissioned you to write a program to help him.

Input

Input will consist of multiple test cases. The first line will contain a single integern indicating the number of orders to deliver, where 1 ≤ n ≤ 10. After this will ben + 1 lines each containing n + 1 integers indicating the times to travel between the pizzeria (numbered 0) and then locations (numbers 1 to n). The jth value on the ith line indicates the time to go directly from location i to locationj without visiting any other locations along the way. Note that there may be quicker ways to go fromi to j via other locations, due to different speed limits, traffic lights, etc. Also, the time values may not be symmetric, i.e., the time to go directly from locationi to j may not be the same as the time to go directly from locationj to i. An input value of n = 0 will terminate input.

Output

For each test case, you should output a single number indicating the minimum time to deliver all of the pizzas and return to the pizzeria.

Sample Input

30 1 10 101 0 1 210 1 0 1010 2 10 00

Sample Output

8



#include<cstdio>
#include<cstring>
using namespace std;

const int N=15;

int dp[1<<N][N],f[N][N];
int Max,n,i;

int main()
{
    for (;;)
    {
    scanf("%d",&n);
    if (n==0) break;
    for (int i=0;i<=n;++i)
    for (int j=0;j<=n;++j)
        scanf("%d",&f[i][j]);
    for (int k=0;k<=n;++k)
    for (int i=0;i<=n;++i)
    for (int j=0;j<=n;++j)
        if (f[i][k]+f[k][j]<f[i][j]) f[i][j]=f[i][k]+f[k][j];
    memset(dp,-1,sizeof(dp));
    Max=1<<(n+1);
    dp[1][0]=0;
    for (i=1;i<Max;++i)
    {
        i=i|1;
        for (int j=0;j<=n;++j)
            if (dp[i][j]!=-1)
            {
                for (int k=0;k<=n;++k)
                    if (k!=j&&(dp[(1<<k)|i][k]==-1||dp[(1<<k)|i][k]>dp[i][j]+f[j][k]))
                        dp[(1<<k)|i][k]=dp[i][j]+f[j][k];
            }
    }
    printf("%d\n",dp[Max-1][0]);
    }    
    return 0;
}


0 0
原创粉丝点击