位运算/二进制题单(一)

CF 2189 C2 XOR-convenience (Hard Version)

\(n\) 为奇数时,直接让 \(a[n]=1\) 就行

但当 \(n\) 是偶数时,如果最后一个是 \(1\),则 \(a[1]\) 就会出问题

所以可以让:

a[1]=a[lowbit(n)];
a[lowbit(n)]=n;
点击查看代码
#include<bits/stdc++.h>
#define int long long
using namespace std;
using pii=pair<int,int>;
using ll = long long;
using ull = unsigned long long;
const ll inf = 1e18;
const int mod = 998244353;

int lowbit(int x){
    return x&-x;
}

void solve(){   
    int n;
    cin>>n;

    if(n==lowbit(n)){
        cout<<-1<<endl;
        return;
    }

    vector<int> a(n+1),cnt(n+1);
    a[n]=1;
    cnt[1]=1;

    for(int i=2;i<n;i++){
        a[i]=i^1;
        cnt[a[i]]++;
    }
    for(int i=1;i<=n;i++){
        if(!cnt[i]) a[1]=i;
    }

    if((n&1)==0){
        a[1]=a[lowbit(n)];
        a[lowbit(n)]=n;
    }

    for(int i=1;i<=n;i++){
        cout<<a[i]<<" ";
    }
    cout<<endl;

}

signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0);

    int ct=1;
    cin>>ct;

    while(ct--){
        solve();
    }
}

CF 1775C Interesting Sequence

点击查看代码
#include<bits/stdc++.h>
#define int long long
using namespace std;
using pii=pair<int,int>;
using ll = long long;
using ull = unsigned long long;
const ll inf = 1e18;
const int mod = 998244353;

int lowbit(int x){
    return x&-x;
}

void solve(){
    int n,x;
    cin>>n>>x;
    
    if((n|x)!=n){
        cout<<-1<<endl;
        return;
    }
    if(n==x){
        cout<<n<<endl;
        return;
    }
    int pos=0;

    for(int j=62;j>=0;j--){
        if((n>>j)  & 1){
            pos=j;
            break;
        }
    }
    int ans=n;
    for(int j=pos;j>=0;j--){
        if(((x>>j) & 1) == 0 && ((n>>j) & 1)){
            
            for(int k=j-1;k>=0;k--){
                if((ans>>k) & 1){
                    ans^=(1ll<<k);
                }
            }
            // cout<<ans<<endl;

            ans+=(1ll<<j);
            if((n & ans) == x) cout<<ans<<endl;
            else cout<<-1<<endl;
            return;
        }
    }
    
}

signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0);

    int ct=1;
    cin>>ct;

    while(ct--){
        solve();
    }
}
posted @ 2026-03-17 16:56  LYET  阅读(10)  评论(0)    收藏  举报