纬度打击 2021-03-25 15:22 采纳率: 88.9%
浏览 9

hdu1251,为什么我的代码是WA的,哪位大佬帮我看看?

这是我的代码:

#include<cstring>
#include<cstdio>
#include<cmath>
#include<string>

using namespace std;

struct trie {
    int nex[100000][26], cnt;
    bool exist[1000000];//该结点结尾的字符串是否存在

    void insert(char *s, int l) {//插入字符串
        int p = 0;
        for (int i = 0; i < l; i++) {
            int c = s[i] - 'a';
            if (!nex[p][c]) {
                nex[p][c] = ++cnt;
            }
            p = nex[p][c];
            exist[p]+=1;
        }
    }

    bool find(char *s, int l) {//查找字符串
        int p = 0;
        for (int i = 0; i < l; i++) {
            int c = s[i] - 'a';
            if (!nex[p][c]) return 0;
            p = nex[p][c];
        }
        return exist[p];
    }
};

trie tri;
char str[23];
int len;

int main() {
    while (gets(str)) {
        len = strlen(str);
        if (len == 0) break;
        tri.insert(str, len);
    }
    while (gets(str)) {
        len = strlen(str);
        printf("%d\n", tri.find(str, len));
    }

    return 0;
}

这是别人的代码:

#include<cstring>
#include<cstdio>

using namespace std;

const int maxn=500000;
char wen[20];

struct node{
    int tot;
    int child[26];
    node(){
        tot=0;
        memset(child,0,sizeof(child));
    }
}tree[maxn];

int sz=0;

void insert(char *s){
    int u=0;
    int h=strlen(s);
    for(int i=0;i<h;i++){
        int pos=s[i]-'a';
        if(tree[u].child[pos]==0){
            tree[u].child[pos]=++sz;
        }
        u=tree[u].child[pos];
        tree[u].tot++;
    }
}

int find(char *t){
    int u=0;
    int h=strlen(t);
    for(int i=0;i<h;i++){
        int pos=t[i]-'a';
        if(tree[u].child[pos]==0){
            return 0;
        }
        u=tree[u].child[pos];
    }
    return tree[u].tot;
}

int main(){
    while(gets(wen)){
        if(strlen(wen)==0)  break;
        insert(wen);
    }
    while(gets(wen)){
        printf("%d\n",find(wen));
    }
    return 0;
}
  • 写回答

1条回答 默认 最新

  • CSDN-Ada助手 CSDN-AI 官方账号 2022-09-07 17:34
    关注
    不知道你这个问题是否已经解决, 如果还没有解决的话:

    如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 以帮助更多的人 ^-^
    评论

报告相同问题?

悬赏问题

  • ¥15 电子档案元素采集(tiff及PDF扫描图片)
  • ¥15 flink-sql-connector-rabbitmq使用
  • ¥15 zynq7015,PCIE读写延时偏大
  • ¥15 使用spss做psm(倾向性评分匹配)遇到问题
  • ¥20 vue+UEditor附件上传问题
  • ¥15 想做个WPS的自动化代码,不知道能做的起不。
  • ¥15 uniApp,生成安卓安卓包后,黑暗主题中间内容不生效,底部导航正常
  • ¥15 斯坦福自动漂移非线性模型反解
  • ¥15 学习Python如何找兼职
  • ¥15 python结合Matlab仿真忆阻器