sum
Hey, welcome to HDOJ(Hangzhou Dianzi University Online Judge).
In this problem, your task is to calculate SUM(n) = 1 + 2 + 3 + ... + n.
Hey, welcome to HDOJ(Hangzhou Dianzi University Online Judge).
In this problem, your task is to calculate SUM(n) = 1 + 2 + 3 + ... + n.
1 100
1 5050
代码:
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
int c[100000];
int m;
int lowbit(int x)
{
return x&(-x);
}//他接下来会修改的
int sum(int end)
{
int ans=0;
while(end>0)
{
ans=ans+c[end];
end=end-lowbit(end);
}
return ans;
}//求1到end的和
void change(int x,int p)//将第x个数加p
{
while(x<=m)
{
c[x]+=p;
x+=lowbit(x);
}
return;
}
int main()
{
while(scanf("%d",&m)!=EOF)
{
memset(c,0,sizeof(c));
for(int i=1;i<=m;i++)
change(i,i);
printf("%d\n\n",sum(m));
}
return 0;
}