Description
给定 \(A,B,N\) ,求 \(\sum\limits_{i=1}^{N} popcount(B+i*A)\) ,其中 \(popcount\) 是指数 \(x\) 在二进制下 \(1\) 的个数。
多组数据。
数据范围 \(1\le T\le 20, 1\le A\le 10000, 1\le B\le 10^{16}, 1\le N\le 10^{12}\)
时间限制 \(2000\ ms\)
空间限制 \(128\ MB\)
Solution
对每位进行分析。
对于第 \(i\) 位,我们发现,这 \(n\) 个数每经过 \(2^{i+1}\) 就一循环,因为 \(2^{i+1} * x\) 在二进制下末 \(i+1\) 位均为 \(0\) 。
所以,我们可以对于这些循环的批量做,剩余的那些同样这么做即可。
具体见代码。
复杂度 \(O(\frac{x}{x/a})=O(a)\)
Code
// Author: wlzhouzhuan
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define rint register int
#define rep(i, l, r) for (rint i = l; i <= r; i++)
#define per(i, l, r) for (rint i = l; i >= r; i--)
#define mset(s, _) memset(s, _, sizeof(s))
#define pb push_back
#define pii pair <int, int>
#define mp(a, b) make_pair(a, b)
inline int read() {
int x = 0, neg = 1; char op = getchar();
while (!isdigit(op)) { if (op == '-') neg = -1; op = getchar(); }
while (isdigit(op)) { x = 10 * x + op - '0'; op = getchar(); }
return neg * x;
}
inline void print(int x) {
if (x < 0) { putchar('-'); x = -x; }
if (x >= 10) print(x / 10);
putchar(x % 10 + '0');
}
ll T, a, b, n;
ll calc(ll l, ll r, ll mod, ll base) {
ll ret = 0;
for (ll i = l, j; i <= r; i = j + 1) {
ll x = (b + a * i) % mod;
if (x >= base) { // 这一位上是1
j = min(r, i + (mod - 1 - x) / a);
ret += j - i + 1;
} else { // 这一位上是0
j = min(r, i + (base - 1 - x) / a);
}
}
return ret;
}
int main() {
cin >> T;
while (T--) {
cin >> a >> b >> n;
ll maxx = b + a * n, ans = 0;
for (ll x = 1, mod = 2; x <= maxx; x <<= 1, mod <<= 1) {
ans += (n / mod) * calc(1, mod, mod, x) + calc(1, n % mod, mod, x);
}
cout << ans << '\n';
}
return 0;
}