题目链接:点击打开链接
大意:n组数据,每组给一个l, r,求出一个x,使得x >= l && x <= r,且x的二进制表示中1的数量最多(多种情况输出最小的)
思路:ans初始化为二进制数位全为1、大于r的数。然后从最高位开始操作,变为1,若ans >= l && ans <= r,ans即为所求若ans>r,则向前一位,若ans<l则不能变为1,向前一位继续变(解释得我自己都看不懂。。。)
代码:
#include<cstdio> #include<cstdlib> #include<cmath> #include<cstring> #include<string> #include<iostream> #include<algorithm> #include<iomanip> #include<map> #include<vector> #include<set> #define FAST ios::sync_with_stdio(false) typedef long long ll; using namespace std; int main() { FAST; int t; cin >> t; while(t--){ ll l, r; cin >> l >> r; ll ans = (1LL << 60) - 1; for(int i = 59; i >= 0; i--){ if(ans >= l && ans <= r) break; if((ans ^ (1LL << i)) < l) continue; ans ^= (1LL << i); } cout << ans << endl; } return 0; }over