HDU 1556 Color the ball
转载请注明出处:http://blog.csdn.net/a1dark
分析:学树状数组的时候遇到了这题、仔细一看发现可以用前缀数组轻松AC、于是便用前缀数组AC之、代码如下:
#include<stdio.h> #include<string.h> int a[100005]; int main(){ int n,x,y,i; while(scanf("%d",&n)!=EOF){ memset(a,0,sizeof(a)); if(n==0)break; for(i=1;i<=n;i++){ scanf("%d%d",&x,&y); a[x]++;a[y+1]--; } for(i=2;i<=n;i++) a[i]+=a[i-1]; for(i=1;i<=n;i++){ if(i==1) printf("%d",a[i]); else printf(" %d",a[i]); } printf("\n"); } return 0; }
但是毕竟是在学树状数组、所以还是用树状数组再次AC之、
#include<stdio.h> #include<string.h> int sum[100005]; int n; int lowbit(int x){ return x&(-x); } int getsum(int x){ int s=0; while(x>0){ s+=sum[x]; x-=lowbit(x); } return s; } void update(int x,int num){ while(x<=n){ sum[x]+=num; x+=lowbit(x); } } int main(){ int i,x,y; while(scanf("%d",&n)!=EOF){ if(n==0)break; memset(sum,0,sizeof(sum)); for(i=1;i<=n;i++){ scanf("%d%d",&x,&y); update(x,1); update(y+1,-1); } for(i=1;i<=n;i++){ printf("%d",getsum(i)); if(i<n)printf(" "); } printf("\n"); } return 0; }
至于 线段树的方法就不写了、毕竟是道模板题、