题解:P17723 [SCP-S 2026] 函数 / func
首先看到
显然前者更简单。如果只有
现在考虑补充
考虑如何寻找所有满足
最后考虑这些区间的贡献。我们称“
由于外层有对二进制位的枚举,而
至此本题结束。时间复杂度
PS:
- 记得开 unsigned long long;
- 为了卡常,使用了快读,并在其中使用了
getchar_unlocked(),其显著快于getchar(),但是只能在 Linux 环境下编译(Windows 中应使用_getchar_nolock()),但赛后发现没必要卡常,纯是因为本地机子太慢了。
#include<iostream>
#include<vector>
using namespace std;
typedef unsigned long long ull;
typedef pair <int, int> pii;
const int maxn = 2e6 + 5;
int n, a[maxn], p, cnt[maxn], tot;
ull ans, now, lst;
vector <int> v;
vector <pii> v1;
int read(){
char ch = getchar_unlocked();
int res = 0;
while(ch < '0' || ch > '9') ch = getchar_unlocked();
while(ch >= '0' && ch <= '9') res = (res << 3) + (res << 1) + (ch ^ 48), ch = getchar_unlocked();
return res;
}
int main(){
n = read();
for(int i = 1; i <= n; ++i) a[i] = read();
for(int i = 0; i < 30; ++i){
lst = now = 0;
for(int j = 1; j <= n; ++j)
if(a[j] >> i & 1) now += (j - lst) * (n - j + 1), lst = j;
now *= (1 << i);
ans += now;
}
for(int i = 0; i <= 20; ++i){
v.clear();
v1.clear();
tot = p = 0;
for(int j = 0; j < (1 << i); ++j) cnt[j] = 0;
v.push_back(0);
for(int j = 1; j <= n; ++j){
if(a[j] >> i & 1) v.push_back(j);
while(p < n && tot < (1 << i)){
p++;
if(a[p] >= (1 << i)) continue;
cnt[a[p]]++;
if(cnt[a[p]] == 1) tot++;
}
if(tot == (1 << i)) v1.push_back({j, p});
if(a[j] >= (1 << i)) continue;
cnt[a[j]]--;
if(!cnt[a[j]]) tot--;
}
v.push_back(n + 1);
p = -1, now = 0;
for(int j = 0; j < v1.size(); ++j){
while(v[p + 1] < v1[j].first) p++;
if(v[p + 1] <= v1[j].second) continue;
lst = v[p];
if(j) lst = max((int)lst, v1[j - 1].first);
now += (v1[j].first - lst) * (v[p + 1] - v1[j].second);
}
now *= (1 << i);
ans += now;
}
cout << ans;
return 0;
}