对SPOJ PHONELST的错误答案

时间:2016-07-30 13:50:47

标签: c++ trie

以下是问题的链接:http://www.spoj.com/problems/PHONELST/

法官在第二组测试案例中给出了错误的答案。这是我的问题代码,请帮帮我。谢谢。

#include<iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include<vector>
using namespace std;

#define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0])

// Alphabet size (# of symbols)
#define ALPHABET_SIZE (10)

// Converts key current character into index
// use only 'a' through 'z' and lower case 
#define CHAR_TO_INDEX(c) ((int)c - (int)'0')

// trie node
struct TrieNode
{
    struct TrieNode *children[ALPHABET_SIZE];

    // isLeaf is true if the node represents
    // end of a word
    bool isLeaf;
};

// Returns new trie node (initialized to NULLs)
struct TrieNode *getNode(void)
{
    struct TrieNode *pNode = NULL;

    pNode = (struct TrieNode *)malloc(sizeof(struct TrieNode));

    if (pNode)
    {
        int i;

        pNode->isLeaf = false;

        for (i = 0; i < ALPHABET_SIZE; i++)
            pNode->children[i] = NULL;
    }

    return pNode;
}

// If not present, inserts key into trie
// If the key is prefix of trie node, just marks leaf node
bool insert(struct TrieNode *root, string key)
{
    int level;
    int length = key.length();
    int index;

    struct TrieNode *pCrawl = root;

    for (level = 0; level < length; level++)
    {
        index = CHAR_TO_INDEX(key[level]);

        if(pCrawl->isLeaf)
        {
            return 0;
        } 
        else if (!pCrawl->children[index])
        {
            pCrawl->children[index] = getNode();
        }

        pCrawl = pCrawl->children[index];
    }

    // mark last node as leaf
    pCrawl->isLeaf = true;
    return 1;
}
int main()
{
   int t;
   cin>>t;
   while(t--)
   {
       int n;
       cin>>n;
       struct TrieNode *root = getNode();
       vector<string>v;
       bool ok=1;
       string keys;
       for(int z=0;z<n;z++)
       {

            cin>>keys;
            v.push_back(keys);      
       }
       for(int z=0;z<n&&ok;++z)
       {        
             ok=insert(root,v[z]);     
       }     
       if(ok)
            cout<<"YES"<<endl;
       else 
            cout<<"NO"<<endl;
       }
           return 0;
}

1 个答案:

答案 0 :(得分:0)

在向量中插入所有电话号码后,需要对矢量进行排序。原因是如果在没有对数组进行排序的情况下完成插入,对于下面的测试用例,代码会给出错误的答案。
2
91190个
911个
在上述变更之后,法官接受解决方案。