Bessie the Cow has stolen Farmer John’s tractor and is running wild on the coordinate plane! She, however, is a terrible driver, and can only move according to the following rules:
Each of her movements is in the same direction as either the positive xx-axis or the positive yy-axis.
Her nnth movement takes her 2n−12n−1 units forward in her chosen direction. (On her first movement, n=1n=1, so she moves 11 unit.)
Farmer John’s farm is on the coordinate plane, in the shape of a rectangle with corners at (0,0)(0,0), (A,0)(A,0), (0,B)(0,B) and (A,B)(A,B). If Bessie starts at (0,0)(0,0), how many points inside the farm, including the boundary, could she reach?
Input
The input begins with an integer NN (1≤N≤1001≤N≤100) on a line by itself, indicating the number of test cases that follow. Each of the following NN lines contains two space separated integers AA and BB (1≤A,B≤1081≤A,B≤108), describing the upper-right corner of Farmer John’s farm.
Output
Output NN lines, with the NNth line containing the number of points that Bessie could possibly reach in the NNth test case.
In the first test case of the sample, Bessie can reach the following six points: (0,0)(0,0), (0,1)(0,1), (1,0)(1,0), (1,2)(1,2), (2,1)(2,1) and (3,0)(3,0).
Sample Input 1 | Sample Output 1 |
---|---|
2 2 3 7 7 | 6 15 |
#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <vector>
#include <stack>
#include <set>
#include <queue>
#include <map>
#include <algorithm>
using namespace std;
int t, a, b;
int main() {
cin >> t;
while (t--) {
cin >> a >> b;
int ans = 0;
for (int i = 1; ; i = i * 2 + 1) {
int y1 = max(0, i - b), y2 = min(a, i);
if (y1 > a) break;
ans += abs(y1 - y2) + 1;
}
cout << ans + 1 << endl;
}
}