题意:从最上面走到最下面,使得路过的数求和为s,并输出编号最小的一组路径。
析:基本动规,dp[i][j][s] 从最下面到 i,j 和为s,路径数,要么从左面要么从右,求和就好了,注意上面和下面的不太一样,要分别求解。
代码如下:
#pragma comment(linker, "/STACK:1024000000,1024000000") #include <cstdio> #include <string> #include <cstdlib> #include <cmath> #include <iostream> #include <cstring> #include <set> #include <queue> #include <algorithm> #include <vector> #include <map> #include <cctype> #include <cmath> #include <stack> #include <unordered_map> #include <unordered_set> #define debug() puts("++++"); #define freopenr freopen("in.txt", "r", stdin) #define freopenw freopen("out.txt", "w", stdout) using namespace std; typedef long long LL; typedef pair<int, int> P; const int INF = 0x3f3f3f3f; const double inf = 0x3f3f3f3f3f3f; const double PI = acos(-1.0); const double eps = 1e-8; const int maxn = 150 + 5; const int mod = 2000; const int dr[] = {-1, 1, 0, 0}; const int dc[] = {0, 0, 1, -1}; const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"}; int n, m; const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; inline bool is_in(int r, int c){ return r >= 0 && r < n && c >= 0 && c < m; } LL dp[45][25][505]; int a[45][25]; void print(int d, int idx, int ans){ if(d + 1 == 2 * n) return ; if(d < n){ if(1 == d) for(int i = 1; i <= n; ++i)if(dp[d][i][ans]){ printf("%d ", i-1); if(dp[d+1][i-1][ans-a[d][i]]){ putchar('L'); print(d+1, i-1, ans - a[d][i]); return ; } else{ putchar('R'); print(d+1, i, ans - a[d][i]); return ; } } if(dp[d+1][idx-1][ans-a[d][idx]]){ putchar('L'); print(d+1, idx-1, ans - a[d][idx]); return ; } else{ putchar('R'); print(d+1, idx, ans - a[d][idx]); return ; } } else{ if(dp[d+1][idx][ans-a[d][idx]]){ putchar('L'); print(d+1, idx, ans - a[d][idx]); return ; } else{ putchar('R'); print(d+1, idx+1, ans - a[d][idx]); return ; } } } int main(){ while(scanf("%d %d", &n, &m) == 2 && m + n){ for(int i = 1; i <= n; ++i) for(int j = 1; j <= n-i+1; ++j) scanf("%d", &a[i][j]); for(int i = n+1; i < 2*n; ++i) for(int j = 1; j <= i-n+1; ++j) scanf("%d", &a[i][j]); memset(dp, 0, sizeof dp); for(int i = 1; i <= n; ++i) dp[2*n-1][i][a[2*n-1][i]] = 1; for(int i = 2*n-2; i >= n; --i) for(int j = 1; j <= i-n+1; ++j) for(int k = a[i][j]; k <= m; ++k) dp[i][j][k] = dp[i+1][j][k-a[i][j]] + dp[i+1][j+1][k-a[i][j]]; for(int i = n-1; i > 0; --i) for(int j = 1; j <= n-i+1; ++j) for(int k = a[i][j]; k <= m; ++k) dp[i][j][k] = dp[i+1][j][k-a[i][j]] + dp[i+1][j-1][k-a[i][j]]; LL ans = 0; for(int i = 1; i <= n; ++i) ans += dp[1][i][m]; printf("%lld\n", ans); if(ans) print(1, -1, m); printf("\n"); } return 0; }