Aninteresting game
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 541 Accepted Submission(s): 219
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.
对于第一种查询,可得出每加入一个i消耗lowbit(i)的能量,但是从l加到r会超时,所以每次算从第一个到l-1的区间长度总和,再算到r的,他们的值相减即为答案。
算区间总和的方法就是,对于每个区间长度的计算一遍。比如区间长度tmp=2时,x/tmp就是指是二的倍数的那些区间长度的个数,再减去是4的倍数的,避免重复计算,再乘以区间长度就可以得到 这个长度的区间消耗的能量总和。
对于第二种查询,其实就是查询有哪几个集合中可包含x,往上求父节点即可。
Source
#include <iostream>
#include<cstdio>
using namespace std;
long long getsum(long long x)
{
long long ans=0,tmp=1;
for(long long i=0;tmp<=x;i++)
{
ans+=((x/tmp)-(x/(tmp<<1)))*tmp;
tmp=tmp<<1;
}
return ans;
}
int main()
{
long long n,q;
while(cin>>n>>q)
{
int op;
while(q--)
{
scanf("%d",&op);
if(op==1)
{
long long l,r;
scanf("%lld%lld",&l,&r);
printf("%lld\n",getsum(r)-getsum(l-1));
}
else
{
long long x;
scanf("%lld",&x);
long long ans=0;
while(x<=n)
{
ans++;
x+=x&(-x);
}
printf("%lld\n",ans);
}
}
}
return 0;
}