题目链接:https://www.nowcoder.com/acm/contest/16/C
时间限制:1秒
空间限制:131072K
题目描述
考虑维护一个这样的问题:
(1) 给出一个数组A,标号为1~n
(2) 修改数组中的一个位置。
(3) 询问区间[l,r]中所有子集的位运算and之和mod(10 9+7)。
位运算and即为“pascal中的and”和“C/C++中的&”
我们定义集合S={ l , l+1 , ... , r-1 , r}
若集合T,T ∩ S = T,则称T为S的子集
设f(T)=A T1 and A T2 and ... and A Tk (设k为T集大小,若k=0则f(T)=0)
所有子集的位运算and之和即为∑f(T)
那么,现在问题来了。
(1) 给出一个数组A,标号为1~n
(2) 修改数组中的一个位置。
(3) 询问区间[l,r]中所有子集的位运算and之和mod(10 9+7)。
位运算and即为“pascal中的and”和“C/C++中的&”
我们定义集合S={ l , l+1 , ... , r-1 , r}
若集合T,T ∩ S = T,则称T为S的子集
设f(T)=A T1 and A T2 and ... and A Tk (设k为T集大小,若k=0则f(T)=0)
所有子集的位运算and之和即为∑f(T)
那么,现在问题来了。
输入描述:
第一行,一个正整数N 第二行,N个非负整数,为数组A 第三行,一个正整数M,为操作次数 接下来M行格式如下 修改操作: 1 x y,将Ax修改为y 询问操作: 2 l r,区间[l,r]中所有子集的位运算and之和 mod(109+7)
输出描述:
对于每次询问输出一行,为该次询问的答案mod(109+7)。
long long 请使用lld
示例1
输入
3 1 2 3 6 2 1 3 1 1 2 2 1 3 2 2 3 1 2 5 2 1 3
输出
9 15 7 13
说明
第一次询问: Answer =1+2+3+(1 and 2)+(1 and 3)+(2 and 3)+(1 and 2 and 3) =1+2+3+0+1+2+0 =9 第二次询问: Answer =2+2+3+(2 and 2)+(2 and 3)+(2 and 3)+(2 and 2 and 3) =2+2+3+2+2+2+2 =15 第三次询问: Answer =2+3+(2 and 3) =2+3+2 =7 第四次询问: Answer =2+5+3+(2 and 5)+(2 and 3)+(3 and 5)+(2 and 5 and 3) =2+5+3+0+2+1+0 =13
备注:
M,N≤105,Ai≤109
解析:由于数据比较大1e5,咱可以考虑位运算,就是找每一位的对于最后和的贡献,假设[l, r]第k位的和为p, 贡献为 (2^p-1)*2^k(减一是除去0这种情况),用树状数组维护下就好了,比较恶心就是很容易超时,卡时间过的
借鉴博客:http://www.cnblogs.com/wujiechao/p/7704680.html
代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int mod = 1e9+7ll;
int dp[33][100005];
int a[100005];
int n;
void add(int i, int k, int x)
{
while(k <= n)
{
dp[i][k] += x;
k += k&(-k);
}
}
int sum(int i, int k)
{
int ans = 0;
while(k)
{
ans += dp[i][k];
k -= k&(-k);
}
return ans;
}
LL q_mod(LL a, LL b)
{
LL ans = 1;
while(b)
{
if(b&1) ans = a * ans % mod;
a = a*a%mod;
b >>= 1;
}
return ans;
}
int main()
{
int b[33];
b[0] = 1;
for(int i = 1; i <= 33; i++)
{
b[i] = b[i-1]<<1;
}
scanf("%d", &n);
memset(dp, 0, sizeof(dp));
for(int i = 1; i <= n; i++)
{
scanf("%d", &a[i]);
int s = 1, x = a[i];
while(x)
{
if(x&1) add(s, i, 1);
x >>= 1;
s++;
}
}
int m, op, x, y;
scanf("%d", &m);
while(m--)
{
scanf("%d%d%d", &op, &x, &y);
if(op == 1)
{
int o = a[x];
a[x] = y;
int s = 1;
while(o)
{
if(o&1) add(s, x, -1);
o >>= 1;
s++;
}
s = 1;
o = y;
while(o)
{
if(o&1) add(s, x, 1);
o >>= 1;
s++;
}
}
else
{
long long ans = 0;
for(int i = 1; i <= 32; i++)
{
int p = sum(i, y) - sum(i, x-1);
ans = (ans + (q_mod(2, p) - 1)*b[i-1]%mod) % mod;
}
printf("%lld\n", ans);
}
}
return 0;
}