题目描述
维护一个字符串集合:初始为空,依次处理一些插入操作,并在插入之后输出该字符串在集合中出现的次数。
输入
第一行输入n
接下来n行,每行为一个字符串,依次代表一个待插入的字符串。该字符串一定非空,且仅包含小写英文字母。
输出
对于每个插入操作输出一行一个整数,代表插入该字符串之后,该字符串在集合中出现的次数。
样例输入
6
str
bsny
str
str
bsny
longpo
样例输出
1
1
2
3
2
1
提示
50%数据 2<=n<=5000
100%数据 2<=n<=500000 字符串长度小于等于10
考试的时候写了个离线+sort,效果非常好(100get)。
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
struct ty
{
int id;
char s[11];
}p[500005];
int n,x;
int ans[500005];
bool cmp(ty x,ty y)
{
if(strcmp(x.s,y.s)!=0) return strcmp(x.s,y.s)<0; else return x.id<y.id;
}
int main()
{
cin>>n;
for(int i=1;i<=n;i++)
{
scanf("%s",p[i].s);
p[i].id=i;
}
sort(p+1,p+n+1,cmp);
ans[p[1].id]=1;x=1;
for(int i=2;i<=n;i++)
if(strcmp(p[i].s,p[i-1].s)!=0)
{
x=1;
ans[p[i].id]=1;
}
else
{
x++;
ans[p[i].id]=x;
}
for(int i=1;i<=n;i++) printf("%d\n",ans[i]);
return 0;
}
今天longpo讲了一个新知识:trie树,其实就是用数组来模拟链表,储存字符信息。
特性:空间难以估算
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
char s[15];
int n,tot;
struct ty
{
int Next[27];
int cnt;
void init()
{
cnt=0;
memset(Next,-1,sizeof(Next));
}
}p[2000005];
void insert(char *s)//星号表关联
{
int x=0;
int len=strlen(s+1);
for(int i=1;i<=len;i++)
{
int j=s[i]-'a';
if(p[x].Next[j]==-1)
{
tot++;
p[tot].init();
p[x].Next[j]=tot;
}
x=p[x].Next[j];
}
p[x].cnt++;
printf("%d\n",p[x].cnt);
}
int main()
{
p[0].init();
tot=0;
cin>>n;
for(int i=1;i<=n;i++)
{
scanf("%s",s+1);
insert(s);
}
return 0;
}