hdu 1556 树状数组

本题也可用线段树过,但代码麻烦得多。题意就不用说了,直接上代码吧。

View Code
 1 #include <stdio.h>
2 #include <string.h>
3 #define lowbit(x) ((x)&(-x))
4 int a[100005],n;
5 void update(int x,int y)
6 {
7 while(x <= n)
8 {
9 a[x] += y;
10 x += lowbit(x);
11 }
12 }
13 int getsum(int x)
14 {
15 int ans = 0;
16 while(x > 0)
17 {
18 ans += a[x];
19 x -= lowbit(x);
20 }
21 return ans;
22 }
23 int main()
24 {
25 int i,j;
26 while(scanf("%d",&n) == 1 && n)
27 {
28 memset(a,0,sizeof(a));
29 for(j = 1;j <= n;j ++)
30 {
31 int a,b;
32 scanf("%d %d",&a,&b);
33 update(a,1);
34 update(b+1,-1);
35 }
36 printf("%d",getsum(1));
37 for(i = 2;i <= n;i ++)
38 printf(" %d",getsum(i));
39 puts("");
40 }
41 return 0;
42 }

这道题也可直接用数组过,新学到一种方法。

更新点的时候起点坐标开始是1,结束坐标后一位是-1,然后叠加的每个点的次数。

View Code
 1 #include <stdio.h>
2 int a[100005];
3 int main()
4 {
5 int i,n,p,q,s;
6 while(scanf("%d",&n)==1 && n)
7 {
8 for(i = 1;i <= n;i ++)
9 a[i] = 0;
10 for(i = 1;i <= n;i ++)
11 {
12 scanf("%d %d",&p,&q);
13 a[p] ++;
14 a[q+1] --;
15 }
16 printf("%d",a[1]);
17 s = a[1];
18 for(i = 2;i <= n;i ++)
19 {
20 s += a[i];
21 printf(" %d",s);
22 }
23 puts("");
24 }
25 return 0;
26 }



posted @ 2011-09-27 16:56  zhangteng  阅读(244)  评论(0编辑  收藏  举报