文章

4

粉丝

0

获赞

13

访问

345

头像
前缀字符串 :用前缀树做的,WA,不知道为什么
P1098 中山大学2018年机试
发布于2025年3月7日 18:39
阅读数 86

#include <bits/stdc++.h>
using namespace std;
struct node
{
    int num;
    node*next[26];
};
void init(node*&m)
{
    for(int i=0;i<26;i++)
    {m->next[i]=NULL;}
}
void insert(node*&m,string a)
{
    for(unsigned int i=0;i<a.size();i++)
    {
        if(m->next[a[i]-'a']==NULL)
        {
            node*temp=new node();
            temp->num=1;
            init(temp);
            m->next[a[i]-'a']=temp;
            m=m->next[a[i]-'a'];
        }
        else
  ...

登录查看完整内容


登录后发布评论

2 条评论
admin SVIP
2025年3月7日 21:55

在这个代码的基础上,简单改了一下

#include <bits/stdc++.h>
using namespace std;

struct node {
    int num;
    node* next[26];
};

void init(node* m) {
    for (int i = 0; i < 26; i++) {
        m->next[i] = NULL;
    }
}

void insert(node* root, string a) {
    node* current = root;
    for (char c : a) {
        int idx = c - 'a';
        if (current->next[idx] == NULL) {
            node* temp = new node();
            temp->num = 1;
            init(temp);
            current->next[idx] = temp;
        } else {
            current->next[idx]->num++;
        }
        current = current->next[idx];
    }
}

bool is_leaf(node* m) {
    for (int i = 0; i < 26; i++) {
        if (m->next[i] != NULL) {
            return false;
        }
    }
    return true;
}

int leaf(node* m) {
    if (m == NULL) {
        return 0;
    } else if (is_leaf(m)) {
        return 1;
    } else {
        int ans = 0;
        for (int i = 0; i < 26; i++) {
            ans += leaf(m->next[i]);
        }
        return ans;
    }
}

int main() {
    int n;
    while (cin >> n && n != 0) {
        node* root = new node();
        init(root);
        for (int i = 0; i < n; i++) {
            string a;
            cin >> a;
            insert(root, a);
        }
        cout << leaf(root) << endl;
    }
    return 0;
}

 

赞(1)

sheep276 : 回复 admin: 我知道了,我的insert函数没写好,感谢

2025年3月8日 12:26