1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| #include <stdio.h>
int findleftk(int a[],int lo,int hi,int k){ if(hi-lo<=2){ if(a[lo]>=k) return lo; else if(a[lo+1]>=k) return lo+1; else return lo+2; } else{ int mid=(lo+hi)/2; if(a[mid]<k) return findleftk(a,mid+1,hi,k); else return findleftk(a,lo,mid+1,k); } }
int findrightk(int a[],int lo,int hi,int k){ if(hi-lo<=2){ if(a[lo+1]<=k) return lo+1; else if(a[lo]<=k) return lo; else return lo-1; } else{ int mid=(lo+hi)/2; if(a[mid]>k) return findrightk(a,lo,mid,k); else return findrightk(a,mid,hi,k); } }
void quicksort(int a[],int b[],int lo,int hi){ int n=hi-lo,i=lo,j=hi-1; if(n<=1) return; else{ int t=a[lo],p=b[lo]; while(i<j){ while(i<j && a[j]>t) j--; if(i<j){ a[i]=a[j]; b[i++]=b[j]; } while(i<j && a[i]<t) i++; if(i<j){ a[j]=a[i]; b[j--]=b[i]; } } a[i]=t; b[i]=p; quicksort(a,b,lo,i); quicksort(a,b,i+1,hi); } }
int main(){ int n,m,i,j,k,p,q; scanf("%d %d",&n,&m);
int a[n],b[n],sum[n]; for(i=0;i<n;i++) scanf("%d %d",&a[i],&b[i]); quicksort(a,b,0,n);
sum[0]=b[0];
for(i=1;i<n;i++) sum[i]=sum[i-1]+b[i];
for(i=0;i<m;i++){ scanf("%d %d",&p,&q); j=findleftk(a,0,n,p); k=findrightk(a,0,n,q); if(j<=k) printf("%d\n",sum[k]-sum[j]+b[j]); else printf("0\n"); } return 0; }
|