1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
#include <iostream>
#include <cmath>
#include <fstream>
using namespace std;
ifstream in("matrix.in");
long long int result(long long int N, long long int R, long long int S, long long int E, long long int inverse)
{
// reached the base case
if (N==0)
return inverse;
const long long int half = pow(2, N-1);
// if R is in the upper half
if (R < half)
{
if (E<half) /*if the sum required is in the first quarter*/
return result(N-1, R, S, E, inverse);
else if (S>=half) /*if the sum required is in the second quarter*/
return result(N-1, R, S-half, E-half, inverse);
else /*if the sum required is shared between the first and the second quarter*/
return ( result(N-1, R, S, half-1, inverse)+result(N-1, R, 0, E-half, inverse) );
}
// if R is in the lower half
else
{
if (E<half) /*if the sum required is in the third quarter*/
return result(N-1, R-half, S, E, inverse);
else if (S>=half) /*if the sum required is in the fourth quarter*/
return result(N-1, R-half, S-half, E-half, inverse*-1);
else /*if the sum required is shared between the third and the fourth quarter*/
return ( result(N-1, R-half, S, half-1, inverse)+result(N-1, R-half, 0, E-half, inverse*-1) );
}
}
int main()
{
long long int N, R, S, E;
in>>N>>R>>S>>E;
while (N!=-1 && R!=-1 && S!=-1 && E!=-1)
{
cout<<result(N, R, S, E, 1)<<endl;
in>>N>>R>>S>>E;
}
return 0;
}
|