【问题标题】:Codeforces 4C Runtime Error [closed]Codeforces 4C运行时错误[关闭]
【发布时间】:2023-10-08 20:51:01
【问题描述】:

您好,我正在使用 Trie 实现来解决这个问题,但是在 codeforces 的服务器上我遇到了运行时错误,并且在我的电脑和 Ideone 上是正常的。 有任何想法吗 ? http://codeforces.com/contest/4/problem/C https://ideone.com/dvRL3b

#include <cstdio>
#include <string>
#include <iostream>
#include <algorithm>


using namespace std;
#define MAXN  ('z'-'a'+2)
#define VALUE(c) ( (c)-'a' )

struct Trie
{
    Trie *m[MAXN];
    int count;
}trie;

int insert(Trie *  t, char * w){
    if(w[0]=='\0'){
        t->count++;
        return t->count;
    }
    if(t->m[VALUE(w[0])] == NULL){
        t->m[VALUE(w[0])] =(Trie *) malloc(sizeof(Trie));
    }
    return insert(t->m[VALUE(w[0])] , w+1);
}   


int main(){

    int t;
    scanf("%d",&t);

    for (int i = 0; i < t; ++i)
    {
        char *w = NULL;
        w = (char *)malloc(sizeof(char));
        scanf("%s",w);
        //printf("%s\n", w);
        int resp = insert(&trie,w); 
        if(resp > 1){
            printf("%s%d\n", w,resp-1);
        }else{
            printf("OK\n");
        }
    }


    return 0;

}

【问题讨论】:

  • malloced 节点不能保证在mcount 中保持NULLs 和0。当您分配 trie 的新节点时,请用您希望它保存的零填充它。可以使用memset,例如memset (t-&gt;m[VALUE(w[0])], 0, sizeof(Trie));,在malloc之后的那一行。
  • @Gassa 是的,这也是问题所在。谢谢。

标签: c++ algorithm trie


【解决方案1】:

这一行:

w = (char *)malloc(sizeof(char));

只会分配一个字节的内存。

这个问题的请求最多32个字符所以试试:

w = (char *)malloc(sizeof(char)*33); // include 1 extra byte for zero termination byte

此外,在为每个新的 Trie 分配内存时,您可能应该使用 calloc,即更改

t->m[VALUE(w[0])] =(Trie *) malloc(sizeof(Trie));

t->m[VALUE(w[0])] =(Trie *) calloc(sizeof(Trie),1);

否则指针将不会被清除。

【讨论】:

  • 不,仍然是运行时错误。 ://
  • 除此之外,数组和变量计数没有被初始化。解决了这个问题谢谢。