题目
让我们回顾一下,数组 a 的递增子序列是指在不改变其余元素顺序的情况下,通过移除某些元素而得到的序列,并且其余元素是严格递增的(即 ab1<ab2<⋯<abk和 b1<b2<⋯<bk )。注意,空子序列也是递增的。
给你一个正整数 X。你的任务是找出一个长度至多为 200200 的整数数组,使得它有恰好 X 个递增的子序列,或者报告说没有这样的数组。如果有多个答案,你可以打印其中任何一个。
如果两个子序列由相同的元素组成,但在数组中对应不同的位置,则认为它们是不同的(例如,数组 [2,2] 有两个不同的子序列等于[2] )。
输入
第一行包含一个整数 t ( 1≤t≤1000 ) - 测试用例数。
每个测试用例的唯一一行包含一个整数 X( 2≤X≤10^18 )。
输出
对于每个查询,打印其答案。如果无法找到所需的数组,则在第一行打印 -1。否则,在第一行打印正整数 n - 数组的长度。在第二行打印 n个整数--所需的数组本身。如果有多个答案,可以打印任意一个。数组的所有元素都应在 [−10^9;10^9] 范围内。
样例
4
2
5
13
37
1
0
3
0 1 0
5
2 2 3 4 2
7
-1 -1 0 0 2 3 -1
分析
考虑连续几个从大到小的元素有几个排列C(n,1), C(n, 2), C(n, 3)有2^n-1种排列,还有空序列也是一种,对于1 2 3这样一个序列有8种方式,如果再往后面加一位如3,那么能增加3,1 3,2 3,1 2 3四种方案,也就是2^2种方式,也就是说如果序列够长1 2 3.....n,那么我在后面放一个m,那就能增加2^(m - 1)种方式,那么就可以通过二进制来解决该问题
可行性:
首先1 2 3...n的长度由二进制中首位1决定
int ans = 0;
while((1ll << ans) <= n) ans ++;
ans --;
if(a.size() == 0) {
for(int i = 1; i <= ans; i ++) a.push_back(i);
}
那么最多占60余位,若二进制中每一位均为1,那么就会再加上60余位,共120余位,满足不多余200的要求
实现:
暴力:
直接枚举二进制中最前面1的位置
while((1ll << ans) <= n) ans ++;
优化:
利用lowbit快速获取最后一位1来倒序实现
代码
#include<bits/stdc++.h>
using namespace std;
#define x first
#define y second
#define Yes cout << "Yes\n"
#define No cout << "No\n"
#define YES cout << "YES\n"
#define NO cout << "NO\n"
#define ls u << 1
#define rs u << 1 | 1
#define all(x) x.begin(),x.end()
#define int long long
#define i128 __int128
inline int gcd(int a, int b) {return b > 0 ? gcd(b, a % b) : a;}
inline int lowbit(int x) {return x & (-x);}
int qmi(int a, int b, int mod){int res = 1;while(b) {if(b & 1) res = res * a % mod;a = a * a % mod;b >>= 1;}return res;}
inline i128 read(){i128 x = 0, f = 1;char ch = getchar();while(ch < '0' || ch > '9'){if(ch == '-')f = -1;ch = getchar();}while(ch >= '0' && ch <= '9'){x = x * 10 + ch - '0';ch = getchar();}return x * f;}
inline void print(i128 x){if(x < 0){putchar('-');x = -x;}if(x > 9)print(x / 10);putchar(x % 10 + '0');}
typedef long long ll;
typedef pair<int, int> PII;
typedef pair<PII, int> PIII;
const int N = 1e5 + 10, inf = 0x3f3f3f3f, mod = 1e9 + 7;
/*
int mp[N + 1];
vector<int>prim;
void primes() {
for (int i = 2; i <= N; i++) {
if (!mp[i]) {
mp[i] = i;
prim.push_back(i);
}
for (auto p : prim) {
if (i * p > N) break;
mp[i * p] = p;
if (i % p == 0) break;
}
}
}
*/
/*
int fact[N], infact[N]; // 组合数
int C(int a, int b) {return fact[a] * infact[b] % mod * infact[a - b] % mod;}
void combination() {fact[0] = infact[0] = 1;for(int i = 1; i < N; i ++) {fact[i] = fact[i - 1] * i % mod;infact[i] = fact[i] * qmi(i, mod - 2, mod) % mod;}}
*/
void solve()
{
int n; cin >> n;
vector<int>a;
while(n) {
int ans = 0;
while((1ll << ans) <= n) ans ++;
ans --;
if(a.size() == 0) {
for(int i = 1; i <= ans; i ++) a.push_back(i);
}
else a.push_back(ans + 1);
n -= (1ll << ans);
}
if(a.size() <= 200) {
cout << a.size() << '\n';
for(auto t : a) cout << t << ' ';
cout << '\n';
}
else cout << -1 << '\n';
}
signed main()
{
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
int t = 1;
cin >> t;
while (t--)
{
solve();
}
}