这章的作业是第十章的内容,也就是字典。不过我实现这题的时候还是用了之前的数组方法,所以一直有三个点TEL。之前的算法的耗时主要在快排上,O(nlogn)。这次在复习,刚好前几天看hash,想说这题应该也可以用hash实现,下午敲了一下,AC了,把代码贴上来。
#include <iostream>
#include <cstdio>
#include <algorithm>
#define LL __int64//注意这题分数可能为10^18,所以用int64
#define N 1000003
#define MOD 1000003
using namespace std;
LL cnt[N],has[N];
bool vis[N];
//int ans[1007];
inline LL Hash(LL x){//跟上次一样的hash函数
int y=(x%MOD+MOD)%MOD;
while(vis[y]&&has[y]!=x)
y=(y+1)%MOD;
return y;
}
int main(){
int n;
scanf("%d",&n);
memset(cnt,0,sizeof(cnt));
memset(vis,false,sizeof(vis));
LL x,y;
for(int i=1;i<=n;i++)
{
scanf("%I64d",&x);
y=Hash(x);
has[y]=x;
cnt[y]++;
vis[y]=true;
printf("%I64d\n",cnt[y]);
}
return 0;
}
用hash就很简单了,注意大概因为关键字的原因,我用VC6.0的时候用hash是可以的,但是在学校机房用stidio2010就提示错误,所以还是改成了Hash。这样就过了。复杂度就O(n)。