1. 程式人生 > >SPOJ Find the max XOR value(二進制,貪心即可)

SPOJ Find the max XOR value(二進制,貪心即可)

push line def pow 技術 精度問題 上界 分享 map

You have two integers L and R, and you are required to find the max xor value of a and b where L <= a <= R and L <= b <= R

Input

Two integers in a line. L, R <= 1e9

Output

One integer, the answer

Example

Input:
1 10

Output:
15

題意:

給定L,R,X1^X2^X3...最大異或,(L<=X1,X2,X3...<=R)。

沒什麽思路,上次CF就遇到這道題,我是用貪心寫的,忽略pow的精度問題,可以AC。

http://codeforces.com/contest/912/problem/B

技術分享圖片
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<string>
#include<vector>
#include<iostream>
#include<map>
using
namespace std; long long a,b,n,k,ans,c,d; map<long long,int>mp; vector<long long>S; int main() { while(~scanf("%I64d%I64d",&n,&k)){ ans=0; for(long long i=log2(n);i>=0;i--){ long long tmp=pow(2,i); if(k>0){ k
--; mp[tmp]=1; S.push_back(tmp); ans+=tmp; } else{ int L=S.size(); for(int j=0;j<L;j++){ if(mp[S[j]]==1&&S[j]+tmp<=n&&mp[S[j]+tmp]==0) { mp[S[j]]=0; mp[S[j]+tmp]=1; ans+=tmp; S.push_back(S[j]+tmp); break; } } } } printf("%I64d\n",ans); } return 0; }
View Code

但是仔細一想的話,得到了最大了2^n<=R,如果還可以異或一個,那麽選擇2^n-1就好了。(2^n)xor(2^n-1) =2^(n+1)-1。一定是最大的。

比如2^=10000, n=4,10000 xor 01111 = 11111;不可能還有不這個大的了,畢竟n=4是上界。當然只能選一個的時候,就選本身就好了。當然,為了避免卡精度問題(比如CF就hack我了),pow函數最好比較一下,這裏太懶,算了。

#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
int main()
{
    int a,b,ans,L,R;
    while(~scanf("%d%d",&L,&R)){
        if(L==R) printf("%d\n",L);
        else {
            int a=log2(R);
            a=q_pow(2,a);
            printf("%d\n",a+a-1);
        }
    } return 0;
}

SPOJ Find the max XOR value(二進制,貪心即可)