codeforces 400E. Inna and Binary Logic 线段树

时间:2024-10-12 19:05:43

题目链接

给出n个数, 定义a[1][i]为这初始的n个数, 然后a[i][j] = a[i-1][j]&a[i-1][j-1], 这样就可以得到一个三角形一共n*(n-1)/2个数。

给出一种操作, 将a[1][x]这个位置的数换为y, 然后求换完之后的这n(n-1)/2个数的和。

很有意思的题, 这个题应该按位建线段树, 这样需要建18棵, 因为a[1][i]的最大值为1e5。

然后我们来看具体如何做, 我们来看一组数据:3 6 7, 换为二进制之后是下面这个样子。

0 1 1

1 1 0

1 1 1

我们先来算一算这三个数的值为多少, 3+6+7+2+6+2 = 26。

我们发现第一个数和第二个数&之后剩余的是2, 第二个数和第三个数&之后剩余的是6, 我们来观察二进制, 发现第一个数和第二个数的第二位的2个1是相邻的, 并且这一位换成10进制正好是2, 而第二个数和第三个数的第一位和第二位的两个1是相邻的, 换成10进制之后是6。

由此可以推断出, 如果是一个单独的1, 那么贡献就是1, 两个相邻的1贡献是2*3/2 = 3,n个相邻的1贡献就是n(n+1)/2。

那么我们建立线段树的时候就应该保存一个sum, prefix, 以及suffix, 具体的看代码。

 #include <iostream>
#include <vector>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <map>
#include <set>
#include <string>
#include <queue>
#include <stack>
#include <bitset>
using namespace std;
#define pb(x) push_back(x)
#define ll long long
#define mk(x, y) make_pair(x, y)
#define lson l, m, rt<<1
#define mem(a) memset(a, 0, sizeof(a))
#define rson m+1, r, rt<<1|1
#define mem1(a) memset(a, -1, sizeof(a))
#define mem2(a) memset(a, 0x3f, sizeof(a))
#define rep(i, n, a) for(int i = a; i<n; i++)
#define fi first
#define se second
typedef pair<int, int> pll;
const double PI = acos(-1.0);
const double eps = 1e-;
const int mod = 1e9+;
const int inf = ;
const int dir[][] = { {-, }, {, }, {, -}, {, } };
const int maxn = 1e5+;
ll cal(ll val) {
return 1LL*val*(val+)/;
}
struct SegmentTree
{
ll sum[maxn<<], pre[maxn<<], suf[maxn<<];
void pushUp(int rt, int m) {
sum[rt] = sum[rt<<|] + sum[rt<<];
if(pre[rt<<|]&&suf[rt<<]) {
sum[rt] += cal(pre[rt<<|]+suf[rt<<])-cal(suf[rt<<])-cal(pre[rt<<|]);
}
pre[rt] = pre[rt<<];
suf[rt] = suf[rt<<|];
if(pre[rt] == m-(m>>)) {
pre[rt] += pre[rt<<|];
}
if(suf[rt] == m>>) {
suf[rt] += suf[rt<<];
}
}
void update(int p, int val, int l, int r, int rt) {
if(l == r) {
sum[rt] = pre[rt] = suf[rt] = val;
return ;
}
int m = l+r>>;
if(p<=m)
update(p, val, lson);
else
update(p, val, rson);
pushUp(rt, r-l+);
}
}tree[];
int main()
{
int cnt, n, m, x, y, a[];
cin>>n>>m;
for(int i = ; i<=n; i++) {
scanf("%d", &x);
cnt = ;
while(x) {
a[cnt++] = x&;
x>>=;
}
for(int j = ; j<cnt; j++) {
tree[j].update(i, a[j], , n, );
}
}
while(m--) {
scanf("%d%d", &x, &y);
cnt = ;
mem(a);
while(y) {
a[cnt++] = y&;
y>>=;
}
ll ans = , mul = ;
for(int i = ; i<; i++) {
tree[i].update(x, a[i], , n, );
ans += tree[i].sum[]*mul;
mul*=;
}
cout<<ans<<endl;
}
return ;
}