uva116 Unidirectional TSP(DP)

题目链接:

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=11&page=show_problem&problem=52

 

水题

#include <iostream>
#include <cstring>
#include <stack>
#include <cstdio>
#define inf 0x3f3f3f3f
using namespace std;
int n,m;
int a[15][110];
int dp[15][110],fuck[110];
int DP(int x,int y){
    if(dp[x][y]!=inf) return dp[x][y];
    if(y==m-1) return dp[x][y]=a[x][y];
    int ret=inf;
    ret=min(min(DP((x-1+n)%n,y+1),DP(x,y+1)),DP((x+1)%n,y+1));
    return dp[x][y]=ret+a[x][y];
}
int main(){
    freopen("116","r",stdin);
    //freopen("ac.out","w",stdout);
    while(cin>>n>>m){
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                cin>>a[i][j];
            }
        }
        memset(dp,0x3f,sizeof dp);
        int ans=1000000000,pos=n;
        for(int i=0;i<n;i++){
            if(DP(i,0)<ans){
                ans=DP(i,0);
                pos=i;
            }
        }
        int k=0;
        fuck[k++]=pos;
        int j=pos;
        for(int i=1;i<m;i++){
           if(j==n-1){
              if(dp[(j+1)%n][i]+a[j][i-1]==dp[j][i-1]){
                  fuck[k++]=(j+1)%n;j=(j+1)%n;continue;
              }
              if(dp[(j-1+n)%n][i]+a[j][i-1]==dp[j][i-1]){
                  fuck[k++]=(j-1+n)%n;j=(j-1+n)%n;continue;
              }
              if(dp[j][i]+a[j][i-1]==dp[j][i-1]){
                  fuck[k++]=j;continue;
              }
           }
           if(j==0){
              if(dp[j][i]+a[j][i-1]==dp[j][i-1]){
                  fuck[k++]=j;continue;
              }
              if(dp[(j+1)%n][i]+a[j][i-1]==dp[j][i-1]){
                  fuck[k++]=(j+1)%n;j=(j+1)%n;continue;
              }
              if(dp[(j-1+n)%n][i]+a[j][i-1]==dp[j][i-1]){
                 fuck[k++]=(j-1+n)%n;j=(j-1+n)%n;continue;
              }
           }
           if(dp[(j-1+n)%n][i]+a[j][i-1]==dp[j][i-1]){
               fuck[k++]=(j-1+n)%n;j=(j-1+n)%n;continue;
           }
           if(dp[j][i]+a[j][i-1]==dp[j][i-1]){
               fuck[k++]=j;continue;
           }
           if(dp[(j+1)%n][i]+a[j][i-1]==dp[j][i-1]){
               fuck[k++]=(j+1)%n;j=(j+1)%n;continue;
           }
        }
        for(int i=0;i<k;i++){
           if(i) cout<<" ";
           cout<<fuck[i]+1;
        }
        cout<<endl;
        cout<<ans<<endl;
    }
    return 0;
}
uva116

 

posted @ 2014-02-09 20:19  wonderzy  阅读(163)  评论(0编辑  收藏  举报