TLE in the backtracking + bitmasking approach

The code below is giving TLE. As far as taught, this is the best approach for this question but still giving TLE.
More over, the same code gives score of 66 and 83 when run again.
#include<bits/stdc++.h>
using namespace std;

int getPosition(int n) {
int pos = 0;
while(n) {
pos++;
n >>= 1;
}
return pos-1;
}

void solve(int row_mask, int ld, int rd, int row, int done, int &ans, int n, int board[][100]) {
// base case
if(row_mask == done) {
ans++;
return;
}
int safe = done & (~(row_mask | ld | rd));
// find the solution for all set bits in safe
while(safe) {
int p = safe & (-safe);
int col = getPosition§;
board[row][col] = 1;
safe = safe - p;
// recursive call
solve(row_mask | p, (ld | p) << 1, (rd | p) >> 1, row+1, done, ans, n, board);
// backtrack if not able to place all queens safely
board[row][col] = 0;
}
}

int main() {
int n;
cin >> n;
int board[100][100] = {0};
int ans = 0;
// done is the mask denoting work is finished
int done = (1 << n) - 1;
solve(0, 0, 0, 0, done, ans, n, board);
cout << ans;
return 0;
}

Hi

Paste your code on https://ide.codingblocks.com/ and share link. some compilation errors in your code.

Hi,

@sanjeetboora I guess their is some issue with test case please check. Optimised code is also giving TLE for last 3 test cases

Hi

@tusharsk can you please tell me this problem’s name.

Hi
@sanjeetboora problem name is : N queen Hard

Thanks for reporting :slight_smile: the test cases and constraints are updated.

Hi

@sanjeetboora Thank you for your support!

Hi

@Sanyam-Dhawan-1683301181765225 try your code once more if you are still getting TLE do post.

Hit like if you get it! :stuck_out_tongue:
Cheers!

Without answr, how an this be marked rsolved??

Without answering, how an this be marked rsolved??

Hi

Their was issue in test cases, that has been corrected at backend, 3 test cases that were showing TLE has been corrected, you can try running your code now ( i can not run your as it is having compilation error, first correct them and try to run your code, if you are still getting TLE, you can post again in this same thread )

and post your ide link of your code DO NOT DIRECTLY PASTE CODE.

Try submitting your code again and let me know the result here.