tire超时,改用map
查看原帖
tire超时,改用map
1250563
Celestinefly楼主2024/4/4 19:07

tire树(超时了,还没有ac)

#include<iostream>
#include<algorithm>

#include<cstring>
using namespace std;

//trie tree
const int N=1e4+10;
int tree[N][26],cnt[N],idx;
int m,n;
//建树
void build(string s){
    int p=0;
    for(int i=0;s[i];i++){
        int j=s[i]-'a';
        if(!tree[p][j]) tree[p][j]=++idx;
        p=tree[p][j];
    }
    cnt[p]++;
}

int query(string s){
    int p=0;
    for(int i=0;s[i];i++){
        int j=s[i]-'a';
        if(!tree[p][j]) return 0;
        p=tree[p][j];
    }
    if(cnt[p]==1){
        cnt[p]++;
        return 1;
    }else if(cnt[p]==0){
        return 0;
    }else{
        return 2;
    }
}
int main(){
    scanf("%d",&n);
    while(n--){
        char name[50];
        scanf("%s",name);
        build(name);
    }
    scanf("%d",&m);
    while(m--){
        char namex[50];
        scanf("%s",namex);
        int x=query(namex);
        if(x==0) printf("WRONG\n");
        else if(x==1) printf("OK\n");
        else printf("REPEAT\n");
    }
    return 0;
}

map(已经ac,但是不是很开心,因为tire还没有debug,呜呜呜)

#include<iostream>
#include<algorithm>

#include<cstring>
using namespace std;

//trie tree
const int N=1e4+10;
int tree[N][26],cnt[N],idx;
int m,n;
//建树
void build(string s){
    int p=0;
    for(int i=0;s[i];i++){
        int j=s[i]-'a';
        if(!tree[p][j]) tree[p][j]=++idx;
        p=tree[p][j];
    }
    cnt[p]++;
}

int query(string s){
    int p=0;
    for(int i=0;s[i];i++){
        int j=s[i]-'a';
        if(!tree[p][j]) return 0;
        p=tree[p][j];
    }
    if(cnt[p]==1){
        cnt[p]++;
        return 1;
    }else if(cnt[p]==0){
        return 0;
    }else{
        return 2;
    }
}
int main(){
    scanf("%d",&n);
    while(n--){
        char name[50];
        scanf("%s",name);
        build(name);
    }
    scanf("%d",&m);
    while(m--){
        char namex[50];
        scanf("%s",namex);
        int x=query(namex);
        if(x==0) printf("WRONG\n");
        else if(x==1) printf("OK\n");
        else printf("REPEAT\n");
    }
    return 0;
}
2024/4/4 19:07
加载中...