problem url: http://acm.timus.ru/problem.aspx?space=1&num=1028
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

using
namespace
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];
using
namespace
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];
}
else if(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]);
}
}
两种方法解决星系问题
本文介绍了使用哈希表和线段树两种方法来解决一个特定的问题,即计算星星的位置级别。通过这两种方法,可以有效地处理大规模数据集,并提供了一种时间复杂度分别为O(Nsqrt(N))和O(Nlog(N))的解决方案。
355

被折叠的 条评论
为什么被折叠?



