URAL1029. Ministry(DP+路径)

链接

路径麻烦啊 很多细节 倒回去搜一遍

卡了一节数据库。。

  1 #include <iostream>
  2 #include<cstdio>
  3 #include<cstring>
  4 #include<algorithm>
  5 #include<stdlib.h>
  6 using namespace std;
  7 #define LL long long
  8 int u,o,path[50010],flag;
  9 LL sum[110][510],dp[110][510],f[110][510];
 10 int m,n;
 11 void dfs(int u,int v)
 12 {
 13     if(flag)
 14     return ;
 15     int i,j,tt=o;
 16     if(v==1)
 17     {
 18         o++;
 19         path[o] = u;
 20         for(i = o ; i > 1 ; i--)
 21         printf("%d ",path[i]);
 22         printf("%d\n",path[1]);
 23         flag = 1;
 24         return ;
 25     }
 26     if(dp[v][u]==dp[v-1][u]+f[v][u])
 27     {
 28         o = tt;
 29         path[++o] = u;
 30         dfs(u,v-1);
 31     }
 32     for(i = u-1; i >= 1 ; i--)
 33     {
 34         if(dp[v][i]!=dp[v-1][i]+f[v][i])
 35         continue;
 36         o = tt;
 37         if(dp[v][u]==dp[v][i]+sum[v][u]-sum[v][i])
 38         {
 39             for(j = u ; j>= i ; j--)
 40             path[++o] = j;
 41             dfs(i,v-1);
 42         }
 43     }
 44     for(i = u+1 ; i <= m ; i++)
 45     {
 46         if(dp[v][i]!=dp[v-1][i]+f[v][i])
 47         continue;
 48         o = tt;
 49         if(dp[v][u]==dp[v][i]+sum[v][i-1]-sum[v][u-1])
 50         {
 51             for(j = u; j <= i; j++)
 52             path[++o] = j;
 53             dfs(i,v-1);
 54         }
 55     }
 56     o = tt;
 57 }
 58 int main()
 59 {
 60     int i,j,g;
 61     flag=0;
 62     scanf("%d%d",&n,&m);
 63     for(i = 1; i <= n ;i++)
 64     {
 65         for(j = 1; j <=m ; j++)
 66         {
 67             scanf("%lld",&f[i][j]);
 68             sum[i][j] = sum[i][j-1]+f[i][j];
 69         }
 70     }
 71     for(i = 1 ;i <= n ;i++)
 72     {
 73         for(j = 1; j <=m ; j++)
 74         dp[i][j] = dp[i-1][j]+f[i][j];
 75         for(j = 1; j <= m ; j++)
 76         {
 77             for(g = 1; g < j ;g++)
 78             dp[i][j] = min(dp[i][j],dp[i][g]+sum[i][j]-sum[i][g]);
 79             for(g = j+1 ; g <=m ; g++)
 80             dp[i][j] = min(dp[i][j],dp[i][g]+sum[i][g-1]-sum[i][j-1]);
 81         }
 82     }
 83     LL ans = dp[n][1],u = 1;
 84     for(i = 1; i <= m ; i++)
 85     {
 86         if(ans>=dp[n][i])
 87         {
 88             ans = dp[n][i];
 89             if(dp[n][i]==dp[n-1][i]+f[n][i])
 90             u = i;
 91         }
 92     }
 93     o++;
 94     path[o] = u;
 95     if(n==1)
 96     printf("%d\n",u);
 97     else
 98     dfs(u,n-1);
 99     return 0;
100 }
View Code

 

posted @ 2013-09-04 15:07  _雨  阅读(223)  评论(0编辑  收藏  举报