sudama_bera

meet_in_the_middle, xor Path

May 31st, 2026 (edited)
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.46 KB | Source Code | 0 0
  1. void solve() {
  2.     ll n,m,k;cin>>n>>m>>k;
  3.    // total number of moves == distance bet n-1,m-1 and 0,0 i.e n+m-2
  4.     // 2^(n+m-1) possible choises total
  5.     vector<vector<ll>>grid(n,vector<ll>(m));
  6.     for(int i=0;i<n;i++){
  7.         for(int j=0;j<m;j++){
  8.             cin>>grid[i][j];
  9.         }
  10.     }
  11.     vector<vector<map<ll,ll>>>left(n,vector<map<ll,ll>>(m));
  12.     ll ans=0;
  13.     int left_moves=(n+m-2)/2;
  14.     for(int i=0;i<(1<<left_moves);i++){
  15.         int r=0,c=0;
  16.         bool in_grid=true;
  17.         ll xor_sum=grid[0][0];
  18.         for(int j=0;j<left_moves;j++){
  19.             if(i&(1<<j)){
  20.                 r++;
  21.             }else{
  22.                 c++;
  23.             }
  24.             if(r>=n||c>=m){
  25.                 in_grid=true;
  26.                 break;
  27.             }
  28.             xor_sum=xor_sum^(grid[r][c]);
  29.         }
  30.         if(in_grid){
  31.            left[r][c][xor_sum]++;
  32.         }
  33.     }
  34.   int right_moves=(n+m-2)-left_moves-1;
  35.   for(int i=0;i<(1<<right_moves);i++){
  36.     int r=n-1,c=m-1;
  37.     ll xor_sum=grid[n-1][m-1];
  38.     bool in_grid=true;
  39.     for(int j=0;j<right_moves;j++){
  40.      if(i&(1<<j)){
  41.         r--;
  42.      }else{
  43.         c--;
  44.      }
  45.      if(r<0||c<0){
  46.         in_grid=false;
  47.         break;
  48.      }
  49.      xor_sum=xor_sum^grid[r][c];
  50.     }
  51.     if(in_grid){
  52.         ll need=xor_sum^k;
  53.         if(r>0){
  54.             ans+=left[r-1][c][need];
  55.         }
  56.         if(c>0){
  57.             ans+=left[r][c-1][need];
  58.         }
  59.     }
  60.   }
  61.   cout<<ans<<endl;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment