codeforces - 276D【贪心+数学】

     D. Little Girl and Maximum XOR
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

A little girl loves problems on bitwise operations very much. Here's one of them.

You are given two integers l and r. Let's consider the values of for all pairs of integersa and b(l ≤ a ≤ b ≤ r). Your task is to find the maximum value among all considered ones.

Expression means applying bitwise excluding or operation to integersx and y. The given operation exists in all modern programming languages, for example, in languagesC++ and Java it is represented as "^", inPascal — as «xor».

Input

The single line contains space-separated integers l andr (1 ≤ l ≤ r ≤ 1018).

Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use thecin, cout streams or the%I64d specifier.

Output

In a single line print a single integer — the maximum value of for all pairs of integers a, b (l ≤ a ≤ b ≤ r).

Examples
Input
1 2
Output
3
Input
8 16
Output
31
Input
1 1
Output
0


题意:给定 l,r。求l <= a <= b <= r。使得 a^b 最大1

题解:贪心,从最高为往最低位考虑。找到第一个l为0,r为1的位置pos,那么a^b最大值就是 pow(2, pos+1)-1;

           注意预处理出所有的 pow(2, i),或者使用快速幂,不然会精度损失。

代码:

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstring>
 4 #include <cstdio>
 5 #include <bitset>
 6 #include <vector>
 7 #include <queue>
 8 #include <stack>
 9 #include <cmath>
10 #include <list>
11 #include <set>
12 #include <map>
13 #define rep(i,a,b) for(int i = a;i <= b;++ i)
14 #define per(i,a,b) for(int i = a;i >= b;-- i)
15 #define mem(a,b) memset((a),(b),sizeof((a)))
16 #define FIN freopen("in.txt","r",stdin)
17 #define FOUT freopen("out.txt","w",stdout)
18 #define IO ios_base::sync_with_stdio(0),cin.tie(0)
19 #define mid ((l+r)>>1)
20 #define ls (id<<1)
21 #define rs ((id<<1)|1)
22 #define N 1000+5
23 #define INF 0x3f3f3f3f
24 #define INFF 0x3f3f3f3f3f3f3f
25 typedef long long ll;
26 const ll mod = 20071027;
27 const ll eps = 1e-12;
28 using namespace std;
29 
30 ll l,r,dp[63];
31 int main()
32 {
33     dp[1] = 1;
34     rep(i, 2, 62)    dp[i] = dp[i-1]*2;
35     while(cin >> l >> r){
36         int id = -1,bit = 1;
37         while(l || r){
38             if(r&1 && !(l&1))    id = bit;
39             bit++;
40             l >>= 1;
41             r >>= 1;
42         }
43         cout << (id == -1 ? 0 : dp[id+1]-1) << endl;
44     }
45     return 0;
46 }
View Code

 

posted on 2017-01-16 20:31  Jstyle  阅读(236)  评论(0编辑  收藏  举报

导航