Problem Description
Let’s play a game.We add numbers 1,2...n in increasing order from 1 and put them into some sets.
When we add i,we must create a new set, and put iinto it.And meanwhile we have to bring [i-lowbit(i)+1,i-1] from their original sets, and put them into the new set,too.When we put one integer into a set,it costs us one unit physical strength. But bringing integer from old set does not cost any physical strength.
After we add 1,2...n,we have q queries now.There are two different kinds of query:
1 L R:query the cost of strength after we add all of [L,R](1≤L≤R≤n)
2 x:query the units of strength we cost for putting x(1≤x≤n) into some sets.
When we add i,we must create a new set, and put iinto it.And meanwhile we have to bring [i-lowbit(i)+1,i-1] from their original sets, and put them into the new set,too.When we put one integer into a set,it costs us one unit physical strength. But bringing integer from old set does not cost any physical strength.
After we add 1,2...n,we have q queries now.There are two different kinds of query:
1 L R:query the cost of strength after we add all of [L,R](1≤L≤R≤n)
2 x:query the units of strength we cost for putting x(1≤x≤n) into some sets.
Input
There are several cases,process till end of the input.
For each case,the first line contains two integers n and q.Then q lines follow.Each line contains one query.The form of query has been shown above.
n≤10^18,q≤10^5
For each case,the first line contains two integers n and q.Then q lines follow.Each line contains one query.The form of query has been shown above.
n≤10^18,q≤10^5
Output
For each query, please output one line containing your answer for this query
Sample Input
10 2 1 8 9 2 6
Sample Output
9 2Hintlowbit(i) =i&(-i).It means the size of the lowest nonzero bits in binary of i. For example, 610=1102, lowbit(6) =102= 210 When we add 8,we should bring [1,7] and 8 into new set. When we add 9,we should bring [9,8] (empty) and 9 into new set. So the first answer is 8+1=9. When we add 6 and 8,we should put 6 into new sets. So the second answer is 2.
题意:
将1-n个数从小到大放入集合,每次你放入新的数i时,需要将[i-lowbit(i)+1,i-1]取出来,再和i一起放入新集合,放一个数耗费一点体力,取数不费体力。
现在有两种操作:
1 L R 将 L到R放入时总共消耗的体力。
2 x 将x移出到新集合所消耗的体力。
解:
进行1操作:
每次添加i时,我们需要体力:(i-1)-(i-lowbit(i)+1)=lowbit(i)点。
但直接枚举累加lowbit(i)的值显然会超时。
那么我们会发现求L到R所消耗的体力其实就是1-R所消耗的体力减去1-(L-1)所消耗的体力。
我们通过求解2的幂次来算出结果。
进行2操作时:
我们会发现,将i进行移动的话,是直接到树状数组的父节点位置,因为在父节点包含的区间里一定有i。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
typedef long long ll;
long long lowbit(long long x){
return x&(-x);
}
ll cal(ll x)
{
ll sum=0;
for(ll i=0;(1ll<<i)<=x;++i)
sum+=(x/(1ll<<i)-x/(1ll<<(i+1)))*(1ll<<i);
return sum;
}
int main()
{
long long n,l,r,ans;
int p,ch;
long long int c;
while(~scanf("%lld%d",&n,&p))
{
while(p--)
{
scanf("%d",&ch);
if(ch==1){
ans=0;
scanf("%lld%lld",&l,&r);
ans=cal(r)-cal(l-1);
}
else{
ans=0;
scanf("%lld",&c);
while(c<=n)
{
ans++;
c+=lowbit(c);
}
}
printf("%lld\n",ans);
}
}
return 0;
}