Power and Zero
[Link](Problem - I - Codeforces)
题意
给你一个序列 A n A_n An,你可以进行多次操作,每次操作可以选择一个任意长度的序列 B m B_m Bm,然后使得 A B i − 2 i − 1 A_{B_i}-2^{i-1} ABi−2i−1。问你最少多少次操作可以将 A n A_n An序列变为零。
题解
发现操作可以等价为满足条件下将某个数二进制下的某一位砍掉,但必须要保证操作序列连续。因此可以将 A n A_n An中的每个数的二进制位分别求出来加在一起,然后问题等价为至少多少次操作将这些二进制的1消除掉,操作等价为消除连续的1。
假设x次操作成立的话那么x+1次操作也一定成立,因此发现具有二段性可以二分,我们从高位到低位枚举要将当前这一位的1全删掉需要的操作数(看看是否可以连续删即可),然后将当前这一位操作后剩下的给前面加上,再每一位都删除相应的数量即可,最后每一次的操作数累加起来就是res。
Code
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <set>
#include <queue>
#include <vector>
#include <map>
#include <bitset>
#include <unordered_map>
#include <cmath>
#include <stack>
#include <iomanip>
#include <deque>
#include <sstream>
#define x first
#define y second
#define debug(x) cout<<#x<<":"<<x<<endl;
using namespace std;
typedef long double ld;
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<double, double> PDD;
typedef unsigned long long ULL;
const int N = 1e5 + 10, M = 2 * N, INF = 0x3f3f3f3f, mod = 1e9 + 7;
const double eps = 1e-8, pi = acos(-1), inf = 1e20;
#define tpyeinput int
inline char nc() {static char buf[1000000],*p1=buf,*p2=buf;return p1==p2&&(p2=(p1=buf)+fread(buf,1,1000000,stdin),p1==p2)?EOF:*p1++;}
inline void read(tpyeinput &sum) {char ch=nc();sum=0;while(!(ch>='0'&&ch<='9')) ch=nc();while(ch>='0'&&ch<='9') sum=(sum<<3)+(sum<<1)+(ch-48),ch=nc();}
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
int h[N], e[M], ne[M], w[M], idx;
void add(int a, int b, int v = 0) {
e[idx] = b, w[idx] = v, ne[idx] = h[a], h[a] = idx ++;
}
int n, m, k;
int a[N];
LL num[33], back[33];
bool check(int pos, int x) {
for (int i = 1; i <= pos; i ++ ) back[i] = num[i];
for (int i = pos; i; i -- ) {
if (back[i] < x) return false;
back[i - 1] += (back[i] - x) * 2;
}
return true;
}
void modify(int pos, int x) {
for (int i = pos; i; i --) {
num[i] -= x;
if (i == pos) num[i - 1] += num[i] * 2;
}
}
int main() {
ios::sync_with_stdio(false), cin.tie(0);
int T;
cin >> T;
while (T -- ) {
cin >> n;
for (int i = 0; i < 32; i ++ ) num[i] = 0;
for (int i = 0; i < n; i ++ ) {
int x; cin >> x;
for (int i = 0; i < 32; i ++ )
if (x >> i & 1) num[i + 1] ++;
}
int res = 0;
for (int i = 32; i; i -- ) {
int l = 0, r = 100010;
while (l < r) {
int mid = (l + r + 1) >> 1;
if (check(i, mid)) l = mid;
else r = mid - 1;
}
modify(i, l);
res += l;
}
cout << res << endl;
}
return 0;
}