欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

CodeForces - 1006F Xor-Paths(双向搜索,到分界位置组合一起和最终结果比较+map容器)

程序员文章站 2022-05-30 21:27:59
...

题目链接https://vjudge.net/contest/348012#problem/D
CodeForces - 1006F Xor-Paths(双向搜索,到分界位置组合一起和最终结果比较+map容器)
CodeForces - 1006F Xor-Paths(双向搜索,到分界位置组合一起和最终结果比较+map容器)
翻译
给定三个数n,m,k
接下来输入一个n*m的地图
求都多少条从(1,1)到(n,m)的不同路径。
这些路径满足的条件是,一条路径上所有点对应的a(i,j)的异或和等于k
分析
从(1,1)直接dfs一直到(n,m)----->超时
优化
从(1,1)到(n,m)需要走n+m-2步,可以从(1,1)和(n,m)同时走,走的步数都为总步数的一半。
mid=(n+m-2)/2
从(1,1)往(n,m)走,假设走到(x,y)时,步数为mid。dfs的过程也记录mp[1][1]~mp[x][y]的异或和。
同时记录这个异或和出现的次数。
再从(n,m)出发,走剩余的步数,dfs过程也得到一个异或和,再相遇处进行处理。
代码

#include<cstdio>
#include<cstring>
#include<map>
#include<algorithm>
using namespace std;
typedef  long long LL;
const int N=25;
map<LL,int>v[N][N];
int n,m;
LL k;
int to[2][2]= {1,0,0,1};
int net[2][2]= {0,-1,-1,0};
LL mp[30][30];
int mid;
LL num;
/*思想:从(1,1)(n,m)总共走n+m-2*/
void dfs1(int x,int y,LL val,int step)
{
    if(step==mid)
    {
        v[x][y][val]++;
        return;
    }
    for(int i=0; i<2; i++)
    {
        int tx=x+to[i][0];
        int ty=y+to[i][1];
        if(tx>=1&&tx<=n&&ty>=1&&ty<=m)
            dfs1(tx,ty,val^mp[tx][ty],step+1);
    }
}
void dfs2(int x,int y,LL val,int step)
{
    if(step==n+m-2-mid)
    {
        num+=v[x][y][k^mp[x][y]^val];/*从走上角到右下角相遇处的mp[x][y]异或了两次*/
        return;
    }
    for(int i=0; i<2; i++)
    {
        int tx=net[i][0]+x;
        int ty=net[i][1]+y;
        if(tx>=1&&tx<=n&&ty>=1&&ty<=m)
            dfs2(tx,ty,val^mp[tx][ty],step+1);
    }
}
int main()
{
    scanf("%d%d%lld",&n,&m,&k);/*n:高度,m:宽度*/
    for(int i=1; i<=n; i++)
        for(int j=1; j<=m; j++)
            scanf("%lld",&mp[i][j]);
    mid=(n+m-2)/2;
    dfs1(1,1,mp[1][1],0);
    dfs2(n,m,mp[n][m],0);
    printf("%lld\n",num);
    return 0;
}

CodeForces - 1006F Xor-Paths(双向搜索,到分界位置组合一起和最终结果比较+map容器)
风花雪月

相关标签: 搜索