3 1 1 2 2 3 3 3 1 1 1 2 1 3 0
1 1 1 3 2 1
原題鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=1556
此題用1般的方法絕對TLE,但是也有高手用數組摹擬過了的,后面也會附上代碼,用線段樹來解決是不錯的選擇。此題可以說是線段樹區間更新的入門題吧,由于更新的時候不1定每次都要更新到每一個葉子節點。詳見代碼。
#include <cstdio> #include <iostream> #include <cstring> using namespace std; const int maxn=100000+5; struct Node { int l,r,cnt; } node[maxn<<2]; void BuildTree(int l,int r,int k) { node[k].l=l; node[k].r=r; node[k].cnt=0; if(l==r) return; int mid=(l+r)>>1; BuildTree(l,mid,k<<1); BuildTree(mid+1,r,k<<1|1); } void UpdateTree(int l,int r,int k) { //只需要在這個區間+1就好了,節省時間,不用找到每一個數 if(node[k].l==l&&node[k].r==r) { node[k].cnt+=1; return; } int mid=(node[k].l+node[k].r)>>1; if(r<=mid) UpdateTree(l,r,k<<1); else if(l>mid) UpdateTree(l,r,k<<1|1); else { UpdateTree(l,mid,k<<1); UpdateTree(mid+1,r,k<<1|1); } } void QueryTree(int k,int sum) { //由于非葉子節點會記錄其子節點的值, //上面留的'坑',并不是所有的葉子節點均被更新 //這也是區間更新的特點 //此題只有1次查詢,所以可以這樣寫 if(node[k].l==node[k].r) { if(node[k].l!=1) printf(" "); printf("%d",node[k].cnt+sum); return; } QueryTree(k<<1,node[k].cnt+sum); QueryTree(k<<1|1,node[k].cnt+sum); } int main() { int n; while(cin>>n,n) { int x,y; //memset(node,0,sizeof(node)); BuildTree(1,n,1); for(int i=0; i<n; i++) { scanf("%d%d",&x,&y); UpdateTree(x,y,1); } QueryTree(1,0); cout<<endl; } return 0; }
#include <cstdio> #include <cstring> #include <iostream> using namespace std; const int maxn=100000+5; int a[maxn]; int main() { int n; while(cin>>n,n) { int x,y; memset(a,0,sizeof(a)); for(int i=0;i<n;i++) { cin>>x>>y; a[x]++; a[y+1]--; } cout<<a[1]; for(int i=2;i<=n;i++) { a[i]+=a[i⑴]; cout<<" "<<a[i]; } cout<<endl; } return 0; }