Pagini recente » Borderou de evaluare (job #1311700) | Cod sursa (job #1967440) | Cod sursa (job #1967441) | Cod sursa (job #1970763) | Cod sursa (job #1212630)
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
typedef unsigned int uint;
struct TrieNode{
bool fullWord;
int wordNumber,fullWordNo;
TrieNode *links[26];
};
TrieNode* createInstance(){
TrieNode *node = new TrieNode;
node->fullWord = false;
node->wordNumber = 0;
node->fullWordNo = 0;
for(int i = 0; i < 26; i++)
node->links[i] = NULL;
return node;
}
void add(TrieNode* root,string w){
TrieNode* current = root;
int offset = 97;
for(uint i = 0; i < w.size(); i++){
if(current->links[w[i] - offset] == NULL)
current->links[w[i] - offset] = createInstance();
current = current->links[w[i] - offset];
current->wordNumber++;
}
current->fullWordNo ++;
current->fullWord = true;
}
void print(TrieNode* root, char branch[],int level){
if(root->fullWord == true){
for(int i = 0; i < level;i++)
cout<<branch[i];
cout<<'\n';
}
for(int i = 0; i < 26; i++){
if(root->links[i] != NULL){
branch[level] = i + 'a';
print(root->links[i],branch,level + 1);
}
}
}
void findWord(TrieNode *root,string word){
for(uint i = 0; i < word.size(); i++){
if(root->links[word[i] - 'a'] != NULL)
root = root->links[word[i] - 'a'];
else{
printf("0\n");
return;
}
}
if(root->fullWord)
printf("%d\n", root->fullWordNo);
else
printf("0\n");
}
void longestPrefix(TrieNode *root,string word){
int maxim = 0;
for(uint i = 0; i < word.size(); i++){
if(root->links[word[i] - 'a'] != NULL){
root = root->links[word[i] - 'a'];
maxim++;
}
else
break;
}
printf("%d\n", maxim);
}
void deleteWord(TrieNode *root, string w,uint index){
if(index < w.size()){
deleteWord(root->links[w[index] - 'a'],w,index + 1);
if(index < w.size()){
if(root->links[w[index] - 'a']->wordNumber > 1)
root->links[w[index] - 'a']->wordNumber--;
else{
free(root->links[w[index] - 'a']);
root->links[w[index] - 'a'] = NULL;
}
}
}
}
int main(){
freopen("trie.in","r",stdin);
freopen("trie.out","w",stdout);
string str;
int q;
TrieNode* root = createInstance();
while(cin>>q>>str){
if(q == 0){
add(root,str);
}
if(q == 1){
deleteWord(root,str,0);
// char branch[20];
// print(root,branch,0);
}
if(q == 2){
// if(str == "abac")
// cout<<"A";
// char branch[20];
// print(root,branch,0);
findWord(root,str);
}
if(q == 3){
longestPrefix(root,str);
}
}
return 0;
}