牛客练习赛37:筱玛的迷阵探险【折半搜索+01字典树】

本文介绍了牛客网的37号练习赛中的迷阵探险问题,提出使用折半搜索配合01字典树的方法来解决。题目要求在n×n的矩阵中寻找从入口(1,1)到出口(n,n)的路径,使得路径上所有数的异或和最大。解决方案中,通过在对角线上建立01字典树,存储路径异或和,结合折半搜索快速找到最大异或值。" 116601825,10546099,Linux环境下DB2数据库安装配置及补丁更新,"['数据库', 'Linux', 'DB2安装', '数据库配置', '数据库管理']

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

链接:https://ac.nowcoder.com/acm/contest/342/C
来源:牛客网

题目:

筱玛是个快乐的男孩子。
寒假终于到了,筱玛决定请他的朋友们一起来玩迷阵探险。
迷阵可以看做一个n×n的矩阵A,每个格子上有一个数Ai,j。
入口在左上角的(1,1)处,出口在右下角的(n,n)处。每一步都只能向下或向右移动一格。最后能获得的经验值为初始经验e与路径上经过的所有数的权值异或和。
求筱玛最大可能获得的经验值。

输入:

第一行两个整数n和e。
接下来n行,每行n个整数,描述矩阵A。

输出:

一个整数,表示筱玛最大可能获得的经验值。

分析:

直接搜肯定超时,考虑折半搜索,用空间换时间,在矩阵对角线上的每个点建一颗字典树,保存从起点到对角线上的异或和的二进制下的01字典树,再从终点搜到对角线,在字典树上查找两边异或的最大值

代码:


#include <iostream>
using namespace std;
int a[22][22],n,e,ans;
struct node
{
    node *Next[2];
};
node *T[22];
node *creat_node()
{
    node *p = new node;
    p->Next[0] = NULL;
    p->Next[1] = NULL;
    return p;
}
void creat_tire(node *head,int x)
{
    node *p = head;
    for(int i = 30; ~i; --i)
    {
        int t = (x>>i) & 1;
        if(p->Next[t] == NULL)
        {
            p->Next[t] = creat_node();
        }
        p = p->Next[t];
    }
}
int query_tire(node *head,int x)
{
    node *p = head;
    int res = 0;
    for(int i = 30; ~i; --i)
    {
        int t = (x>>i) & 1;
        if(p->Next[t^1] != NULL)
        {
            res |= (1<<i);
            t ^= 1;
        }
        p = p->Next[t];
    }
    return res;
}
void init()
{
    for(int i = 1; i <= n; ++i)
        T[i] = creat_node();
}
void dfs1(int x,int y,int v)
{
    int res = 0;
    if(x+y == n+1)
    {
        v ^= a[x][y];
        creat_tire(T[x],v);
        return ;
    }
    dfs1(x+1,y,v^a[x][y]);
    dfs1(x,y+1,v^a[x][y]);
}
void dfs2(int x,int y,int v)
{
    if(x+y == n+1)
    {
        int tep = query_tire(T[x],v);
        ans = max(ans,tep);
        return ;
    }
    dfs2(x-1,y,v^a[x][y]);
    dfs2(x,y-1,v^a[x][y]);
}
int main()
{
    cin>>n>>e;
    init();
    for(int i = 1; i <= n; ++i)
        for(int j = 1; j <= n; ++j)
            cin>>a[i][j];
     dfs1(1,1,e);
     dfs2(n,n,0);
     cout<<ans;
     return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值