N balloons are arranged in a row, numbered 1, 2, 3... from left to right .... n. given two integers a B (A <= B) each time, Lele colors each balloon one time from balloon a to balloon B, riding his "little pigeon" electric car. But after N times, Lele has forgotten how many times the I-th balloon has been painted. Can you help him figure out how many times each balloon has been painted?
#include <cstdlib>#include <iostream>#include<algorithm>#include<cstdio>#include<string.h>#include<string>using namespace std;int num[100006];int lowbit(int x){ return x&(-x);}void updata(int n,int k){ while(n<=100005) { num[n]+=k; n+=lowbit(n); }}int sum(int n){ int res=0; while(n) { res+=num[n]; n-=lowbit(n); } return res; }int main(){ int t; while(~scanf("%d",&t)&&t) { memset(num,0,sizeof(num)); int x,y; for(int i=1;i<=t;i++) { scanf("%d%d",&x,&y); updata(x,1);updata(y+1,-1); } printf("%d ",num[1]); for(int i=2;i<t;i++) printf("%d ",sum(i)); printf("%d\n",sum(t)); // printf("\n"); } //system("PAUSE"); return 0;}
The key to this question is how many times I was operated by updata (x, 1), updata (Y + 1,-1), sum (I) when the array is changed; look for more groups of data to simulate
The following code has the same effect:
#include <iostream> #include<cstdio> #include<string.h> using namespace std;int f[100010]; int main() { int n; int i; while ( scanf("%d",&n) , n ) { memset(f,0,(n+1)*sizeof(int)); for ( i = 0 ; i < n ; ++i ) { int a,b; scanf("%d%d",&a,&b); ++f[a]; --f[b+1]; } int m = 0; for ( i = 1 ; i < n ; ++i ) { m += f[i]; printf("%d ",m); } m += f[i]; printf("%d\n",m); } return 0;}