uva 10564 Paths through the Hourglass

记忆化搜索。注意用 long long

#include <cstdio>
#include <algorithm>
#include <cstring> 
#include <map>
#include <string> 
#include <iostream> 
  
using namespace std;
const int inf  = (-1u>>1);
typedef long long  lld; 
int a[50][25];
lld d[50][25][505];
int n, s; 

void left(int r, int c, int& ans){
     if (r >= 2 * n - 2)ans = -1; 
     else if (c == 0 && (r < n - 1)){ans = -1;} 
     else {
            ans = r < n - 1?c-1:c;
     }
}
void right(int r, int c, int& ans){
     if (r >= 2 * n - 2)ans = -1;
     else if (r < n-1 && c == n-r-1)ans = -1;
     else {
            ans = r < n - 1?c:c + 1;
     }
}
 
      
lld doit(int r, int c, int nu){
    if (d[r][c][nu] != -1)return d[r][c][nu];
    if (r >= 2 * n - 2 ){
          return d[r][c][nu] = (a[r][c] == nu?1:0);
    } 
    d[r][c][nu] = 0;
    if (a[r][c] > nu)return d[r][c][nu]; 
    int dir;
    left(r, c, dir);
    if (dir != -1)d[r][c][nu] += doit(r+1, dir, nu-a[r][c]);
    right(r, c, dir);
    if (dir != -1)d[r][c][nu] += doit(r+1, dir, nu-a[r][c]);
    return d[r][c][nu];
} 
     
     


int main(){
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
    while (scanf("%d %d", &n, &s) == 2 && n+s){
          memset(d, -1, sizeof(d));
          for (int i = 0; i < 2 * n - 1; i++){
              int lmt = (i < n? n - i: i-n+2); 
              for (int j = 0; j < (lmt); j++ ){
                  scanf("%d", &a[i][j]);
              }
          }
          for (int i = 0; i < n; i++)doit(0, i, s);
          lld ans = 0;
          string v;
          int first; 
          for (int i = 0; i < n; i++)if (d[0][i][s] > 0){
              int j = 0;
              int t = i;
              first = t; 
              int res;
              int nu = s; 
              while (j < 2 * n - 1){
                    nu -= a[j][t]; 
                    left(j, t, res);
                    if (res != -1 && d[j+1][res][nu]!=0){
                            v+= 'L';
                    } 
                    else { 
                            right(j, t, res);
                            if (res != -1)v += 'R'; 
                    }
                    t = res;
                    j++;
              }
              break; 
          }
          for (int i = 0; i < n; i++)ans += d[0][i][s];
          printf("%lld\n", ans);
       //  printf("cnt = %d\n", cnt); 
          if (ans != 0){
                  printf("%d ", first);
                  cout<<v; 
          }
          puts("");
    }
    return 0;
} 
                       
               
                     
                                
     
 
 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值