UVA 10564 Paths through the Hourglass
练习打印路径。。本题居然没有PE,搞死我了。。
后来还是参考了一位名为“加速!!!!!!!!!!”的好人的BLOG,自己改了半天才过了。
思路就是dp[i][j][k]代表从(i,j)出发,到达最底层的权值之和为k的路径条数,细节方面小心点。哎~~
贴代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <cstring> 3 #include <cstdio> 4 using namespace std; 5 typedef long long int llg; 6 llg dp[50][50][501]; 7 int left1[50][50]; 8 int right1[50][50]; 9 int h[50][50]; 10 char answer[50]; 11 int nlines; 12 bool ok(int x,int y) 13 { 14 return y > 0 && y <= h[x][0]; 15 } 16 llg DP(int i,int j,int k) 17 { 18 llg &ans = dp[i][j][k]; 19 if(ans != -1) 20 return ans; 21 ans = 0; 22 int x,y; 23 x = i + 1; 24 y = left1[i][j]; 25 if(ok(x,y)) 26 { 27 dp[i][j][k] += DP(x,y,k - h[i][j]); 28 } 29 y = right1[i][j]; 30 if(ok(x,y)) 31 { 32 dp[i][j][k] += DP(x,y,k - h[i][j]); 33 } 34 return ans; 35 } 36 void printans(int i,int j,int k) 37 { 38 if(i == nlines * 2 - 2) 39 return; 40 bool flag = false; 41 int x,y; 42 x = i + 1; 43 y = left1[i][j]; 44 if(ok(x,y) && dp[x][y][k - h[i][j]] > 0) 45 { 46 answer[i] = 'L'; 47 flag = true; 48 printans(x,y,k - h[i][j]); 49 } 50 x = i + 1; 51 y = right1[i][j]; 52 if(!flag && ok(x,y) && dp[x][y][k - h[i][j]] > 0) 53 { 54 answer[i] = 'R'; 55 printans(x,y,k - h[i][j]); 56 } 57 } 58 int main() 59 { 60 int num,i,j,temp; 61 llg total; 62 while(cin>>nlines>>num) 63 { 64 if(nlines == 0 && num == 0) 65 break; 66 for(i = 0;i < nlines;i++) 67 { 68 temp = nlines - i;//本行数字的个数 69 h[i][0] = temp; 70 for(j = 1;j <= h[i][0];j++) 71 { 72 left1[i][j] = j - 1; 73 right1[i][j] = j; 74 cin>>h[i][j]; 75 } 76 } 77 left1[nlines - 1][1] = 1; 78 right1[nlines - 1][1] = 2; 79 for(i = nlines;i < nlines * 2 - 1;i++) 80 { 81 temp = 2 + i - nlines; 82 h[i][0] = temp; 83 for(j = 1;j <= h[i][0];j++) 84 { 85 left1[i][j] = j; 86 right1[i][j] = j + 1; 87 cin>>h[i][j]; 88 } 89 } 90 memset(dp,-1,sizeof(dp)); 91 for(i = 1;i <= h[nlines * 2 - 2][0];i++) 92 { 93 temp = h[nlines * 2 - 2][i]; 94 dp[nlines * 2 - 2][i][temp] = 1; 95 } 96 int start = -1; 97 total = 0; 98 for(i = 1;i <= h[0][0];i++) 99 { 100 total += DP(0,i,num); 101 if(start == -1 && dp[0][i][num] > 0) 102 { 103 start = i; 104 printans(0,i,num); 105 } 106 } 107 if(total) 108 { 109 cout<<total<<endl; 110 cout<<start - 1<<" "; 111 for(i = 0;i < 2 * nlines - 2;i++) 112 cout<<answer[i]; 113 cout<<endl; 114 } 115 else 116 { 117 cout<<"0"<<endl; 118 cout<<endl; 119 } 120 } 121 return 0; 122 }