P13551 ももいろの鍵 题解

· · 题解

题目描述

一个 0 到 n 的排列,将其分为尽量多组(不用相邻),使每组按位与为 0。

思路

考虑将其分为两两一组,其和为 2^{k} - 1,这样两数按位与为 0。可以证明不存在更多的分组,因为单个单个的都不能按位与为 0。

例子:

3 + 4 = 2^{3} - 1$,$3$ 按位与 $4$ 为 $0

可以分完吗?可以。比如一个数 n,我们先找到第一个不小于 n 的 2^{k} - 1,那 n 就和 2^{k} - 1 - n 一组,以此类推,那么就还剩 2^{k} - n - 2 个数,然后重复此操作,可以证明,最后只会剩一个 0(n 为偶数)或不剩(n 为奇数)。

实现

使用递归实现上述过程,用一个数组 t 来表示一个数有没有被分过组,每次用数组 r1 和 r2 记录第 cnt 组的两个数,直到不剩数为止。

代码

#include<bits/stdc++.h>
#define int long long
using namespace std;
int T;
int n,s;
bool t[100005];
int r1[100005],r2[100005],cnt;
bool f;
void solve(int n){//递归
    if(f) return;//其实我也不知道怎么退出的
    if(n<=0){f=1;return;}//要退出
    s=1;
    while(s<n) s=s*2+1;//第一个不小于当前n的2的次方减1
    for(int i=1;i<=n;i++){
        if(t[i]||s-i>n) continue;//被选过或超出范围就不选
        r1[++cnt]=i;//记录
        r2[cnt]=s-i;
        t[i]=t[s-i]=1;//标记
    }
    solve(s-n-1);//往下递归
}
signed main(){
    ios::sync_with_stdio(0);
    cin.tie(NULL),cout.tie(NULL);
    cin>>T;
    while(T--){
        memset(t,0,sizeof(t));//多测不清空,爆零两行泪
        cin>>n;
        if(n==0){//0要特判
            cout<<"1\n1 0\n";
            continue;
        }
        f=0;
        cnt=0;
        solve(n);
        cout<<cnt+(n%2==0?1:0)<<"\n";//如果是偶数就还有一个0
        for(int i=1;i<=cnt;i++) cout<<"2 "<<r1[i]<<" "<<r2[i]<<"\n";
        if(n%2==0) cout<<"1 0\n";//偶数情况
    }
    return 0;
}

最后再强调一次:多测要清空!