下厨房----------------前缀树应用

版权声明:转载请注明出处即可 https://blog.csdn.net/qq_35170212/article/details/81284499

题:
每个输入包含 1 个测试用例。每个测试用例的第 i 行,表示完成第 i 件料理需要哪些材料,各个材料用空格隔开,输入只包含大写英文字母和空格,输入文件不超过 50 行,每一行不超过 50 个字符。
输出描述:
输出一行一个数字表示完成所有料理需要多少种不同的材料。
输入:
BUTTER FLOUR
HONEY FLOUR EGG
输出:
4
手撕:

#include<iostream>
#include<cstring>

using namespace std;

class TrieNode{
public:
    TrieNode* next[27];
    bool isEnd;
    int endCnt;
    TrieNode(){
        isEnd=false;
        endCnt=0;
        memset(next,0,sizeof(next));
    }
};

void hashStrByTrie(TrieNode* root,const string& str,int& res){
    TrieNode* cur=root;
    for(int i=0;i<str.size();++i){
        int index=str[i]-'A';
        if(!cur->next[index])
            cur->next[index]=new TrieNode();        
        cur=cur->next[index];
    }
    if(!cur->isEnd){
        ++res;
        cur->isEnd=true;
    }
    ++(cur->endCnt);    
}

测试:

int main(){
    string curstr;
    TrieNode root;
    int res=0;
    while(cin>>curstr){   //按ctrl+c终止
        hashStrByTrie(&root,curstr,res);
    }
    cout<<res<<endl;
    return 0;
}

题目来源:
https://www.nowcoder.com/practice/ca5c9ba9ebac4fd5ae9ba46114b0f476?tpId=85&tqId=29832&rp=1&ru=/ta/2017test&qru=/ta/2017test/question-ranking

猜你喜欢

转载自blog.csdn.net/qq_35170212/article/details/81284499