poj 2001 Shortest Prefixes

//字典树的入门题,感觉还可以,就是当我用cin输入的时候,我一直在考虑紧,怎样结束输入的,在网上也找了
//很多的解题报告,发觉他们都是用scanf()!= EOF来解决的!而后来再找,原来cin是直接就包含了这一个条件了,
//所以它会自动判断是否输入结束的,提交上去,顺利AC了,如果你想看结果的,就要设置一定条件,使其输入结束! 
//直接套用字典树的模板就可以解决问题! 
#include <iostream>
#include <string>
using namespace std;

struct TireNode{
       int count;
       struct TireNode *branch[26];
       TireNode(){
             count = 0;
             for (int i = 0; i < 26; i++)
                  branch[i] = NULL;
       }
};


void TireInsert(TireNode *&root, string str)
{
     if (root == NULL)
         root = new TireNode();
     int i, len;
     len = str.length();
     TireNode *p = root;
     for (i = 0; i < len; i++){
         if (!p->branch[str[i]-'a'])
             p->branch[str[i]-'a'] = new TireNode();
         p = p->branch[str[i]-'a'];
         p->count++;
     }
     return ;
}


int TireSearch(TireNode *root, string str)
{
     if (root == NULL)
         return 0;
     int i, len;
     string ans;
     len = str.length();
     TireNode *p = root;
     for (i = 0; i < len; i++){
         p = p->branch[str[i]-'a'];
         if (p->count == 1)
              return i;
     }
     return len;
}


int main()
{
    int i, k = 0, pos;
    string word[1010], str, ans;
    TireNode *root = NULL;
    while (cin >> str){
          TireInsert(root, str);
          word[k] = str;
          k++;
    }
    for (i = 0; i < k; i++){
        pos = TireSearch(root, word[i]);
        if (pos != word[i].length())
            pos = pos + 1;
        ans = word[i].substr(0, pos);
        cout << word[i] << " " << ans << endl;
    }
    
    system("pause");
}

你可能感兴趣的:(poj 2001 Shortest Prefixes)