位运算

来源:互联网 发布:数控车床编程基础视频 编辑:程序博客网 时间:2024/05/16 17:11

Bitwise Equations

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 652    Accepted Submission(s): 347


Problem Description
You are given two positive integers X and K. Return the K-th smallest positive integer Y, for which the following equation holds: X + Y =X | Y
Where '|' denotes the bitwise OR operator.
 

Input
The first line of the input contains an integer T (T <= 100) which means the number of test cases. 
For each case, there are two integers X and K (1 <= X, K <= 2000000000) in one line.
 

Output
For each case, output one line containing the number Y.
 

Sample Input
35 15 52000000000 2000000000
 

Sample Output
21816383165351936
 


题意:给你一个数X和K,问你第K小的数Y使得X + Y = X | Y。


思路:显然对于X,若它的二进制位为0,那么Y对应的二进制位可以填0和1;反之Y对应的二进制位只能填0。

因此,只需要预处理X二进制的前i位的合法填数方案vnum[i],这个过程中借助了num[i]——前i位不同的组合数,可能头一位是0。统计前缀和sum。接下来,一步步找好了,填好Y的二进制位,求出Y就可以了。

后来发现自己一开始就想复杂了。。。

先来个与题目无关的代码位运算的巧妙运用a+b:

<span style="font-size:10px;">#include<iostream>//c++#include<cmath>//数学公式#include<cstdlib>//malloc#include<cstring>#include<string>#include<cstdio>//输入输出#include<algorithm>//快排#include<queue>//队列#include<functional>//优先队列#include<stack>//栈#include<vector>//容器#include<map>//地图  if continueusing namespace std;int main(){int i,j,k,a,b,c;int x,y;cin>>a>>b;x=a|b;y=a&b;while(y){       <span style="white-space:pre"></span> <span style="white-space:pre"></span>x=x^y;       <span style="white-space:pre"></span>y<<=1;        <span style="white-space:pre"></span>a=x;        <span style="white-space:pre"></span>b=y;        <span style="white-space:pre"></span>x=a|b;        <span style="white-space:pre"></span>y=a&b;}cout<<x<<endl;return 0;}</span><span style="font-size: 18px;"></span>

本题代码如下:

<span style="font-size:10px;">#include<iostream>//c++#include<cmath>//数学公式#include<cstdlib>//malloc#include<cstring>#include<string>#include<cstdio>//输入输出#include<algorithm>//快排#include<queue>//队列#include<functional>//优先队列#include<stack>//栈#include<vector>//容器#include<map>//地图  if continuetypedef long long ll;const  int N=30;using namespace std;int main(){    //freopen("C:\\Users\\ch\\Desktop\\1.txt","r",stdin);//freopen("C:\\Users\\lenovo\\Desktop\\2.txt","w",stdout);int i,j,k;ll x,n;while(~scanf("%lld%lld",&x,&n)){    ll p=1,ans=0;    while(n)        {            while(x&p) p<<=1;            if(n&1)    ans|=p;            n>>=1;            p<<=1;        }        cout<<ans<<endl;}return 0;}</span><span style="font-size: 18px;"></span>


0 0