思路就是有零一变化的位Or以后一定是1,And以后一定是0;那么如果b的二进制更长那么就把包含a的部分全部置为1或0,如果一样长那么就把不同的部分置为1或0。
今天被这题坑的地方:1默认是int,如果要移到32bits以上要转成long long用1LL,血的教训。以及,数组开得太极限,很容易出错。
#include<cstdio> const int maxlen = 61; typedef long long ll; inline int int2bit(ll x,int *a){ int t = 0; while(x) { a[t] = x&1; x >>= 1; t++; } return t; } const ll one = 1; void solve(ll a,ll b,ll &Or,ll &And) { int b1[maxlen],b2[maxlen]; int l1 = int2bit(a,b1); int l2 = int2bit(b,b2); if(l2>l1){ ll t =(one<<l2)-1; Or = t; And = 0; return; } if(l2 == l1){ int i; for( i = l2-1; i >= 0; i--){ if(b1[i]!=b2[i]) break; } ll t = (one<<(i+1))-1; Or = b|t; And = b&~t; } } int main() { // freopen("in.txt","r",stdin); // freopen("out.txt","w",stdout); int t; scanf("%d",&t); for(int i = 1; i <= t; i++){ ll Or,And,a,b; scanf("%lld%lld",&a,&b); solve(a,b,Or,And); printf("Case %d: %lld %lld ",i,Or,And); } return 0; }