Got two methods here. One uses hash table which will give you O(Nsqrt(N)) , another uses segment tree(binary search..) which gives you O(Nlog(N))
**hash table approach:
#include <cstdio> #include <cstddef> #include <iostream> #include <math.h> #define MAX_XY 32000 #define MAX_COUNT 15000 usingnamespace std; void main() ...{ int count =0; int i=0; int sx,sy; int bSize =0 ; //bucket size int bNum =0; //total bucket number int p[MAX_XY+1] =...{0}; int* lList = NULL; int*b = NULL; scanf("%d", &count); bSize = (int)sqrt((double)MAX_XY); bNum = (MAX_XY+1) / bSize +1; b = (int*)malloc(sizeof(int)*bNum); memset(b, 0, sizeof(int)*bNum); lList = (int*)malloc(sizeof(int) * count); memset(lList, 0, sizeof(int)*count); for(i =0;i<count;++i) ...{ int bCur =0;//current bucket index int lCur =0;//current level scanf("%d %d", &sx, &sy); bCur = sx / bSize; /**/////calculate level int j =0; for(j =0; j<bCur;++j) ...{ lCur += b[j]; } for(j= bSize*bCur; j<=sx; ++j) ...{ lCur += p[j]; } lList[lCur]++; /**//// b[bCur]++; p[sx]++; } //print out result for(i=0;i<count;++i) ...{ printf("%d ",lList[i]); } free(b); free(lList); }
**segment tree approach:
#include <cstdio> #include <cstddef> #include <iostream> #include <math.h> #define MAX_XY 32000 #define MAX_COUNT 15000 int vals[MAX_XY *4+1] =...{0}; int lList[MAX_COUNT]; usingnamespace std; void insertstar(int p, int b, int e, int x) ...{ int m = (b+e) >>1; if(e != b) ...{ if(x <= m) ...{ insertstar(p<<1, b, m, x); }else ...{ insertstar((p<<1)+1, m+1, e, x); } } vals[p] ++; } int getlevel(int p, int b, int e, int x) ...{ int m = (b+e) >>1; if( e == b) ...{ return vals[p]; } else ...{ if( x == e) ...{ return vals[p]; } elseif(x > m) ...{ return getlevel(p<<1, b, m, m) + getlevel((p<<1)+1,m+1, e, x); }else ...{ return getlevel(p<<1, b, m, x); } } } void main() ...{ int count =0; int i=0; int sx,sy; //get star number //cin>>count; scanf("%d", &count); memset(lList, 0, sizeof(int)*MAX_COUNT); for(i =0;i<count;++i) ...{ int lCur =0;//current level //cin>>sx>>sy; scanf("%d %d", &sx, &sy); //get level lCur = getlevel(1, 0, MAX_XY, sx); lList[lCur]++; insertstar(1,0,MAX_XY,sx); /**//// } for(i=0;i<count;++i) ...{ printf("%d ",lList[i]); } }
problem url: http://acm.timus.ru/problem.aspx?space=1&num=1028Got two methods here. One uses hash table which will give you O(Nsqrt(N)) , another uses segment tree(binary search..) which gives you