ZOJ 1675 Push!!

本文介绍了一种解决经典推箱子游戏问题的算法实现。通过记录玩家与箱子的位置状态及所需的最少步骤,采用广度优先搜索策略寻找最优解。文章详细展示了状态记录方式与搜索过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 推箱子的题目,需要记录四个状态量,b[pi][pj][bi][bj]代表人和箱子在某种状态下所需要推动的最小step。

lev是无用记录量,仅作测试使用。

#include <cstdio>
#include 
<string>

int dir[4][2=
{
    
01 }10 }- 10 }0-1 }
}
;

int N, M, a[7][7], b[7][7][7][7];

typedef 
struct
{
    
int bx, by;        // 箱子
    int px, py;        // 人
    int step, lev;        // 步数
}
 Box;
Box q[
2500], c, m, g;

int inline _check ( int i, int j )
{
    
return i >= 0 && i < N && j >= 0 && j < M && a[i][j] == 0;
}


int init ()
{
    scanf ( 
"%d%d"&M, &N );
    
int i, j;
    
for ( i = 0; i < N; i ++ )
        
for ( j = 0; j < M; j ++ )
        
{
            scanf ( 
"%d"&a[i][j] );
            
if ( a[i][j] == 2 )
                c.bx 
= i, c.by = j, a[i][j] = 0;
            
if ( a[i][j] == 3 )
                g.bx 
= i, g.by = j, a[i][j] = 0;
            
if ( a[i][j] == 4 )
                m.px 
= i, m.py = j, a[i][j] = 0;
        }

    memset ( b, 
0xffsizeof ( b ) );
    
return N;
}


void bfs ()
{
    
int pi, pj, pii, pjj, bi, bj, bii, bjj, k, step, lev;
    
int op, ed, ans = 9999;
    q[
0].bx = c.bx, q[0].by = c.by, q[0].px = m.px, q[0].py = m.py;
    q[
0].step = 0, q[0].lev = 0;
    b[q[
0].px][q[0].py][q[0].bx][q[0].by] = 0;
    
int ac;
    
//printf ( "%d %d %d %d ", c.bx, c.by, m.px, m.py );
    for ( op = -1, ed = 0; op ++ < ed; )
    
{
        Box def 
= q[op];
        pi 
= def.px, pj = def.py, bi = def.bx, bj = def.by, step = def.step, lev = def.lev;
        
//pb ( pi, pj, bi, bj, step, lev );
        if ( bi == g.bx && bj == g.by && def.step < ans )
        
{
            
//printf ( "%d %d %d %d ", pi, pj, bi, bj );
            ans = def.step;
        }

        
for ( k = 0; k < 4; k ++ )
        
{
            pii 
= pi + dir[k][0], pjj = pj + dir[k][1];
            bii 
= bi, bjj = bj;
            
if ( _check ( pii, pjj ) )
            
{
                
if ( pii != bi || pjj != bj )    // 人走到空位
                {
                    
if ( b[pii][pjj][bii][bjj] > step || b[pii][pjj][bii][bjj] == -1 )
                    
{
                        q[
++ ed].bx = bii, q[ed].by = bjj, q[ed].px = pii, q[ed].py = pjj;
                        q[ed].step 
= step, q[ed].lev = lev + 1;
                        b[pii][pjj][bii][bjj] 
= step;
                        
//printf ( "%d %d %d %d ", pii, pjj, bii, bjj );
                    }

                }

                
else                                                    // 人推箱子
                {
                    bii 
= bi + dir[k][0], bjj = bj + dir[k][1];
                    
if ( _check ( bii, bjj ) )
                    
{
                        
if ( b[pii][pjj][bii][bjj] > step + 1 || b[pii][pjj][bii][bjj] == -1 )
                        
{
                            q[
++ ed].bx = bii, q[ed].by = bjj, q[ed].px = pii, q[ed].py = pjj;
                            q[ed].step 
= step + 1, q[ed].lev = lev + 1;
                            b[pii][pjj][bii][bjj] 
= step + 1;
                            
//printf ( "%d %d %d %d ", pii, pjj, bii, bjj );
                        }

                    }

                }

            }

        }

    }

    printf ( 
"%d ", ans == 9999 ? -1 : ans );
}


int main ()
{
    
//freopen ( "in.txt", "r", stdin );
    
//freopen ( "q1675.in", "r", stdin );
    
//freopen ( "out.txt", "w", stdout );
    while ( init () )
    
{
        bfs ();
    }

    
return 0;
}
### ZOJ 1500 Pre-Post-erous! 的解法分析 #### 题目解析 该问题的核心在于通过给定的一棵树的前序遍历和后序遍历来唯一确定一棵树,并计算其哈希值。输入中的 `N` 表示树的最大分支数量,而两个字符串分别表示前序遍历和后序遍历的结果。 为了构建唯一的二叉树结构并验证一致性,可以通过模拟的方式逐步重建树节点之间的父子关系[^4]。 --- #### 解决思路 1. **输入处理**: 将每组测试数据拆分为三部分:`N`, 前序序列 (`preorder`) 和 后序序列 (`postorder`)。 2. **合法性校验**: 判断前序和后序是否能够对应同一棵合法的树。如果无法匹配,则直接返回错误提示。 3. **树的重建**: 使用递归方式基于前序和后序来恢复树的结构。 - 前序的第一个字符总是根节点。 - 找到当前子树对应的范围,在后序中找到分割点以划分左子树和右子树。 4. **哈希值计算**: 对于每一颗子树,按照特定规则(如深度优先顺序)生成一个整数值作为最终输出。 以下是具体的 Python 实现: ```python def build_tree(preorder, postorder): if not preorder or not postorder: return None root_val = preorder[0] # 如果只有一个节点 if len(preorder) == 1: assert(postorder[0] == root_val) return (root_val,) # 寻找左右子树分界线 L = 1 while True: if set(preorder[1:L+1]) == set(postorder[:L]): break L += 1 left_pre = preorder[1:1+L] right_pre = preorder[L+1:] left_post = postorder[:L] right_post = postorder[L:-1] return ( root_val, build_tree(left_pre, left_post), build_tree(right_pre, right_post) ) def hash_tree(tree): if tree is None: return 0 elif isinstance(tree, tuple): # Non-leaf node _, left, right = tree return ((hash_tree(left) * 31 + ord(tree[0])) * 37 + hash_tree(right)) % 998244353 else: # Leaf node return ord(tree) def solve(): import sys input_data = sys.stdin.read().strip() lines = input_data.splitlines() results = [] i = 0 while i < len(lines): N_str = lines[i].split()[0] if N_str == '0': break N, pre_seq, post_seq = int(N_str), lines[i+1], lines[i+2] try: tree = build_tree(pre_seq, post_seq) result = hash_tree(tree) results.append(result) except AssertionError: results.append(0) i += 3 for res in results: print(res) # 调用函数解决问题 solve() ``` --- #### 关键点说明 1. **树的重建逻辑**: - 根据前序的第一个元素定位根节点。 - 在后序中查找与前序一致的部分,从而分离出左子树和右子树。 2. **哈希值计算**: - 左子树先被完全访问后再轮到右子树,最后加上根节点贡献。 - 结果取模 $998244353$ 来防止溢出。 3. **边界条件**: - 当遇到单节点或者空树时需特别注意判断。 --- #### 测试样例解释 对于样例输入: ``` 2 abc cba 2 abc bca 10 abc bca 13 abejkcfghid jkebfghicda 0 ``` 程序会逐一读入各组数据,调用上述算法完成树的重建以及哈希值计算,最终得到如下输出结果: ``` 4 1 45 207352860 ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值