Codeforces 484A - Bits (贪心)

来源:互联网 发布:mysql中执行顺序 编辑:程序博客网 时间:2024/06/05 01:08

题意

输出[l, r]中二进制数字最多的数字。

思路

贪心,从r的最高位1开始和l比较,直到pos[r] = 1, pos[l] = 0,这时候就可以把r的当前位置置零,之前的位置全部变成1,这个值显然>= l。

然后还要判断一下,因为可能变了之后的数量还没有变之前多。

代码

  1. #include <cstdio>
  2. #include <stack>
  3. #include <set>
  4. #include <iostream>
  5. #include <string>
  6. #include <vector>
  7. #include <queue>
  8. #include <functional>
  9. #include <cstring>
  10. #include <algorithm>
  11. #include <cctype>
  12. #include <string>
  13. #include <map>
  14. #include <cmath>
  15. #define LL long long
  16. #define SZ(x) (int)x.size()
  17. #define Lowbit(x) ((x) & (-x))
  18. #define MP(a, b) make_pair(a, b)
  19. #define MS(arr, num) memset(arr, num, sizeof(arr))
  20. #define PB push_back
  21. #define F first
  22. #define S second
  23. #define ROP freopen("input.txt", "r", stdin);
  24. #define MID(a, b) (a + ((b - a) >> 1))
  25. #define LC rt << 1, l, mid
  26. #define RC rt << 1|1, mid + 1, r
  27. #define LRT rt << 1
  28. #define RRT rt << 1|1
  29. #define BitCount(x) __builtin_popcount(x)
  30. #define BitCountll(x) __builtin_popcountll(x)
  31. #define LeftPos(x) 32 - __builtin_clz(x) - 1
  32. #define LeftPosll(x) 64 - __builtin_clzll(x) - 1
  33. const double PI = acos(-1.0);
  34. const int INF = 0x3f3f3f3f;
  35. using namespace std;
  36. const int MAXN = 1000000 + 10;
  37. const int MOD = 1e9 + 7;
  38. typedef pair<int, int> pii;
  39. typedef vector<int>::iterator viti;
  40. typedef vector<pii>::iterator vitii;
  41. int main()
  42. {
  43. //ROP;
  44. int T, i, j;
  45. scanf("%d", &T);
  46. while (T--)
  47. {
  48. LL l, r;
  49. cin >> l >> r;
  50. int pos = LeftPosll(r);
  51. LL ans = 0;
  52. for (; pos >= 0; pos--)
  53. {
  54. LL tmp = (r & (1ll << pos));
  55. if (tmp && (l & (1ll << pos)) == 0)
  56. {
  57. pos--;
  58. while (pos >= 0)
  59. {
  60. ans |= (1ll << pos);
  61. pos--;
  62. }
  63. }
  64. else if (tmp) ans |= (1ll << pos);
  65. }
  66. if (BitCountll(ans) < BitCountll(r)) ans = r;
  67. cout << ans << endl;
  68. }
  69. return 0;
  70. }
0 0
原创粉丝点击