HDU Travelling(状态DP)

TSP问题

三进制,用四进制的位运算处理的, 时间稍慢。

///4845004 2011-10-28 22:57:30 Accepted 3001 703MS 14208K 2956 B C++ Geners 
///因为数据范围WA了2次 
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

typedef long long ll;
const int inf=0x3fffffff;
const long long inf2=200000000000ll;
int state[60000];
int cut[20];
int res[40000];
void init ()
{
    state[0]=0;
    res[0]=state[1]=1;
    res[1]=state[2]=2;
    int cnt=1;
    //for (int i=3 ; )
    for (int i=3 ; state[i-3]<(1<<20) ; i+=3)
    {
        state[i]=state[cnt]*4;
        state[i+1]=state[cnt]*4+1;
        state[i+2]=state[cnt++]*4+2;
        //printf("%d  %d  %d\n", state[i], i, cnt);
    }
    cnt=0;
    for (int i=2 ; res[i-2]<(1<<20) ; i++)
    {
        res[i++]=res[cnt]*4+1;
        res[i]=res[cnt++]*4+2;
    }
    cut[0]=3;
    for (int i=1 ; i<15 ; ++i)
        cut[i]=cut[i-1]*4;
}

int n, m;
ll map[11][11],w;
ll dp[1<<20][11];//i状态下,在j位置的权值

bool valid (int sta)
{
    return sta==1 || sta==2;
}

bool valid_ (int sta)
{
    return sta==0 || sta==1;
}
void DP()
{
    int limit=3<<((n-1)<<1);
    //printf("limit==%d\n", limit);
    for (int i=0 ; state[i]<=limit ; ++i)
    {
        for (int j=0 ; j<n ; ++j)
        {
            dp[state[i]][j]=inf2;
        }
    }
    for (int i=0 ; state[i]<=limit ; ++i)
    {
        for (int j=0 ; j<n ; ++j)
        {
            dp[1<<(j<<1)][j]=0;
            int sta=(state[i]&cut[j])>>(j<<1);
            if(sta)//j位不为0
            for (int k=0 ; k<n ; ++k)
            {
                if(k==j)continue;
                if(map[k][j]==inf)continue;//k,j不关联
                if(state[i]&cut[k])//k位不为0
                {
                    int pre=(state[i]^(sta<<(j<<1)))|(sta-1)<<(j<<1);
                    dp[state[i]][j]=min(dp[pre][k]+map[k][j], dp[state[i]][j]);
                }
            }
            //if(dp[state[i]][j]!=inf)printf("state[i]==%d j==%d dp==%I64d sta==%d\n", state[i], j,dp[state[i]][j], sta);
        }
    }
    ll ans=inf2;
    int low=(1<<((n-1)<<1));
    //printf("low==%d\n",low);
    for (int i=0 ; res[i]<=limit ; ++i)
    {
        if(res[i]>=low)
        for (int j=0 ; j<n ; ++j)
            ans=min(dp[res[i]][j],ans);
        //printf("res==%d \n", res[i]);
    }
    printf("%I64d\n",ans==inf2?(-1ll):ans);
}

int main ()
{
    int a,b;
    init();
    while (~scanf("%d%d", &n, &m))
    {
        for (int i=0 ; i<n ; ++i)
        {
            for (int j=0 ; j<n ; ++j)
            {
                map[i][j]=inf;
            }
        }
        for (int i=0 ; i<m ; ++i)
        {
            scanf("%d%d%I64d", &a, &b, &w);
            a--; b--;
            map[a][b]=map[b][a]=w;
        }
        DP();
    }
    return 0;
}


 

你可能感兴趣的:(HDU Travelling(状态DP))