维护集合

题目描述
维护一个字符串集合:初始为空,依次处理一些插入操作,并在插入之后输出该字符串在集合中出现的次数。
输入
第一行输入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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值