题目
给出一些用户的昵称,求各个昵称的使用个数且按字典序排序
分析
虽然可以用快排做出来,但是用哈希去重是一个优秀的选择(代码RE好多次了),所以用哈希存下每种情况,存下个数,并用一个point数组指向下标,差不多了,看代码。
代码
#include <cstdio>
#include <cstring>
#include <algorithm>
#define mod 150001//hash开到1.5倍
using namespace std;
struct hash{char s[101];int num;}sash[mod];
char c,k[101]; int n,point[100001];
int locate(int x){
int pos=x%mod,i=0;
while (i<mod&&sash[(pos+i)%mod].num&&strcmp(sash[(pos+i)%mod].s,k)) i++;//当该位置与当前字符数组不相同且该位置不为空则寻找下一个位置
return (pos+i)%mod;//求哈希值
}
bool cmp(int x,int y){return strcmp(sash[x].s,sash[y].s)<1;}//小于等于(所以要用stable_sort,sort会RE)
void print(int ans){if (ans>9) print(ans/10); putchar(ans%10+48);}//逐字符输出
int main(){
c=getchar();
while (c<48||c>57) c=getchar();
while (c>47&&c<58) n=n*10+c-48,c=getchar();
for (int j=1;j<=n;j++){
memset(k,'\0',sizeof(k)); gets(k);
int keyword=0,pos;
for (int i=0;i<strlen(k);i++){
if (k[i]>64&&k[i]<91) k[i]+=32;//变成小写字母
keyword=(keyword+k[i]*i)%mod;//取哈希值
}
point[j]=pos=locate(keyword);
if (!sash[pos].num)//可以放答案
for (int i=0;i<strlen(k);i++)
sash[pos].s[i]=k[i];
sash[pos].num++;//多了一个昵称
}
stable_sort(point+1,point+1+n,cmp);//快排
for (int i=1;i<=n;i++){
if (!sash[point[i]].num) continue;//如果输出过答案
for (int j=0;j<strlen(sash[point[i]].s);j++) putchar(sash[point[i]].s[j]);
putchar(' '); print(sash[point[i]].num); putchar('\n'); sash[point[i]].num=0;
}
return 0;
}