UVA 10564 Paths through the Hourglass(背包)

时间:2021-09-07 04:48:23

为了方便打印路径,考虑从下往上转移。dp[i][j][S]表示在i行j列总和为S的方案,

dp[i][j][S] = dp[i+1][left][S-x]+dp[i+1][right][S-x]

方案O(2^2*n-1),结果要用long long保存。

#include<bits/stdc++.h>
using namespace std; typedef long long ll;
const int maxn = ,maxs = ;
int hg[maxn<<][maxn];
ll dp[maxn<<][maxn][maxs]; //#define LOCAL
int main()
{
#ifdef LOCAL
freopen("in.txt","r",stdin);
#endif
int n, S;
while(scanf("%d%d", &n, &S) ,n){
int rc = ;
for(int i = n; i > ; i--){
int *h = hg[rc++];
for(int j = ; j <= i; j++){
scanf("%d",h+j);
}
}
for(int i = ; i <= n; i++){
int *h = hg[rc++];
for(int j = ; j <= i; j++){
scanf("%d",h+j);
}
}
rc--;
memset(dp,,sizeof(dp));
for(int j = ; j <= n; j++){
dp[rc][j][hg[rc][j]] = ;
}
while(rc>=n){
for(int j = , mj = (rc-- + ) - n; j <= mj; j++){
int x = hg[rc][j];
ll *f = dp[rc][j];
for(int s = S-x; s >= ; s--){
f[s+x] = dp[rc+][j][s]+dp[rc+][j+][s];
}
}
}
for(int i = ; rc--,i <= n; i++){
for(int j = ; j <= i; j++){
int x = hg[rc][j];
ll *f = dp[rc][j];
for(int s = S-x; s >= ; s--){
f[s+x] = dp[rc+][j-][s]+dp[rc+][j][s];
}
}
}
ll ans = ;
int index = ;
for(int j = ; j <= n; j++){
if(dp[][j][S]){
ans += dp[][j][S];
if(!index) index = j;
}
}
printf("%lld\n",ans);
if(ans){
int j = index, s = S ;
printf("%d ",j-);
rc = n;
for(int i = ; i < rc; i++){
s -= hg[i-][j];
if(dp[i][j-][s]){
putchar('L');
j--;
}else {
putchar('R');
} }
rc = *n-;
for(int i = n; i < rc; i++){
s -= hg[i-][j];
if(dp[i][j][s]){
putchar('L');
}else {
j++;
putchar('R');
}
}
}
puts("");
}
return ;
}