a533中等二進位每個位元的週期計數
CPE:How Many Ones Needed? (UVa 12208)
把區間總位元數拆成前綴函數相減。
解題思路
定義 F(n) 為 0 到 n 所有二進位表示中的 1 總數,n<0 時為 0。第 b 位以長度 2^(b+1) 為週期,前半全 0、後半全 1。設 half=2^b、count=n+1,完整週期貢獻 count//(2half)×half,剩餘部分貢獻 max(0,count%(2half)−half)。
每一位獨立累加就是 F(n),所以 [a,b] 答案為 F(b)−F(a−1)。只需計算不超過 n 的二次冪,避免逐一枚舉數字。0 0 是終止資料,不輸出 Case;答案可能超過 32 位元,使用 long long。
Step-by-step animation
示意:計算 [2,5]
步驟 1 / 3
最低位
0..5 有 6 個數,第 0 位完整三個週期,貢獻 3。
0
1
10
11
100
101
- half
- 1
- F(5)累計
- 3
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <iomanip>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <tuple>
#include <functional>
#include <limits>
#include <cstdint>
#include <cctype>
#include <utility>
using namespace std;
long long prefix(long long n) {
if (n < 0)
return 0;
long long ans = 0, count = n + 1;
for (long long half = 1; half <= n; half *= 2) {
long long period = 2 * half;
ans += count / period * half + max(0LL, count % period - half);
}
return ans;
}
int main() {
long long a, b;
int tc = 0;
while (cin >> a >> b && (a || b))
cout << "Case " << ++tc << ": " << prefix(b) - prefix(a - 1) << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。