UVA 10564 Paths through the Hourglass[DP 打印]

时间:2022-05-23 14:03:16
UVA - 10564

UVA 10564 Paths through the Hourglass[DP 打印]

题意:

要求从第一层走到最下面一层,只能往左下或右下走
问有多少条路径之和刚好等于S? 如果有的话,输出字典序最小的路径。

f[i][j][k]从下往上到第i层第j个和为k的方案数
上下转移不一样,分开处理
没必要判断走出沙漏
打印方案倒着找下去行了,尽量往左走
沙茶的忘注释掉文件WA好多次
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int N=,M=,INF=1e9;
typedef long long ll;
inline int read(){
char c=getchar();int x=,f=;
while(c<''||c>''){if(c=='-')f=-;c=getchar();}
while(c>=''&&c<=''){x=x*+c-'';c=getchar();}
return x*f;
}
int n,s,w[N<<][N];
ll f[N<<][N][M];
void dp(){
memset(f,,sizeof(f));
for(int j=;j<=n;j++)
f[n+n-][j][w[n+n-][j]]=; //xia
for(int i=n+n-;i>=n;i--)
for(int j=;j<=i-n+;j++)
for(int k=w[i][j];k<=s;k++)
f[i][j][k]=f[i+][j][k-w[i][j]]+f[i+][j+][k-w[i][j]];
//shang
for(int i=n-;i>=;i--)
for(int j=;j<=n-i+;j++)
for(int k=w[i][j];k<=s;k++)
f[i][j][k]=f[i+][j][k-w[i][j]]+f[i+][j-][k-w[i][j]]; }
void print(int i,int j,ll k){//printf("print %d %d %d\n",i,j,k);
if(i==n+n-) return;
if(i<n){
if(j>&&f[i+][j-][k-w[i][j]]){
putchar('L');
print(i+,j-,k-w[i][j]);
}else{
putchar('R');
print(i+,j,k-w[i][j]);
}
}else{
if(f[i+][j][k-w[i][j]]){
putchar('L');
print(i+,j,k-w[i][j]);
}else{
putchar('R');
print(i+,j+,k-w[i][j]);
}
}
}
int main(){
//freopen("1.in","r",stdin);
//freopen("1.out","w",stdout);
while(scanf("%d%d",&n,&s)!=EOF&&(n||s)){
memset(w,,sizeof(w));
for(int i=;i<=n;i++)
for(int j=;j<=n-i+;j++) w[i][j]=read();
for(int i=n+;i<=n+n-;i++)
for(int j=;j<=i-n+;j++) w[i][j]=read();
dp();
int p=;
ll sum=;
for(int i=n;i>=;i--) if(f[][i][s]){p=i;sum+=f[][i][s];} printf("%lld\n",sum);
if(p) printf("%d ",p-),print(,p,s);
putchar('\n');
}
}