codeforces C. Bits 贪心

偏执的太偏执、 2022-07-24 09:16 297阅读 0赞

C. Bits

time limit per test

1 second

memory limit per test

256 megabytes

input

standard input

output

standard output

Let’s denote as c097ecd8556f4f8d61d8b143ef6afbc7928fce0b.png the number of bits set (‘1’ bits) in the binary representation of the non-negative integer x.

You are given multiple queries consisting of pairs of integers l and r. For each query, find the x, such that l ≤ x ≤ r, and c097ecd8556f4f8d61d8b143ef6afbc7928fce0b.pngis maximum possible. If there are multiple such numbers find the smallest of them.

Input

The first line contains integer n — the number of queries (1 ≤ n ≤ 10000).

Each of the following n lines contain two integers l**i, r**i — the arguments for the corresponding query (0 ≤ l**i ≤ r**i ≤ 1018).

Output

For each query print the answer in a separate line.

Examples

input

  1. 3
  2. 1 2
  3. 2 4
  4. 1 10

output

  1. 1
  2. 3
  3. 7

Note

The binary representations of numbers from 1 to 10 are listed below:

110 = 12

210 = 102

310 = 112

410 = 1002

510 = 1012

610 = 1102

710 = 1112

810 = 10002

910 = 10012

1010 = 10102

题意: 给定l和r, 求l和r之间的数中二进制中1的个数最多的数是哪一个, 如果有多个答案, 输出最小的那个数.

分析: 我们可以贪心的一步一步的将l的最低位0 变成1, 因为要使1的个数最多, 直到l再取大于r的时候就不能取了,这时候l的二进制中1的数目最多, 并且是最小的.

  1. #include<bits/stdc++.h>
  2. #define inf 0x3f3f3f3f
  3. using namespace std;
  4. typedef long long ll;
  5. typedef pair<int,int> pii;
  6. const int N=100010,MOD=1e9+7;
  7. int main()
  8. {
  9. int n;
  10. cin>>n;
  11. while(n--)
  12. {
  13. ll l,r;
  14. cin>>l>>r;
  15. ll ans=l;
  16. while(l<=r)
  17. {
  18. ans = l;
  19. for(int i=0;i<61;i++){
  20. if(!(l&(1LL<<i))){
  21. l |= 1LL<<i;
  22. break;
  23. }
  24. }
  25. }
  26. cout<<ans<<endl;
  27. }
  28. return 0;
  29. }
  30. #include<bits/stdc++.h>
  31. #define inf 0x3f3f3f3f
  32. using namespace std;
  33. typedef long long ll;
  34. typedef pair<int,int> pii;
  35. const int N=100010,MOD=1e9+7;
  36. int main()
  37. {
  38. int n;
  39. cin>>n;
  40. while(n--)
  41. {
  42. ll l,r;
  43. cin>>l>>r;
  44. ll ans=l;
  45. while(l<=r)
  46. {
  47. ans = l;
  48. ll m = (~l)&(-(~l));
  49. l += m;
  50. }
  51. cout<<ans<<endl;
  52. }
  53. return 0;
  54. }

发表评论

表情:
评论列表 (有 0 条评论,297人围观)

还没有评论,来说两句吧...

相关阅读