Created
January 18, 2015 17:50
-
-
Save HaiyangXu/8b4e89fb076078311cc8 to your computer and use it in GitHub Desktop.
Shortest Proper Prefix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <memory.h> | |
#include <string> | |
#include <stdio.h> | |
#include <queue> | |
#include <stack> | |
using namespace std; | |
struct Trie | |
{ | |
int counts; | |
Trie *child[26]; | |
Trie():counts(0) | |
{ | |
memset(child,0,sizeof(child)); | |
} | |
}; | |
Trie * buid_tree(int n){ | |
Trie *head=new Trie; | |
head->counts=INT_MAX; | |
while(n-- >0) | |
{ | |
string word; | |
cin>>word; | |
Trie *p=head; | |
for(int i=0;i<word.length();i++) | |
{ | |
int next=word[i]-'a'; | |
if(p->child[next]!=0) | |
{ | |
p=p->child[next]; | |
p->counts++; | |
} | |
else | |
{ | |
p->child[next]=new Trie(); | |
p=p->child[next]; | |
p->counts++; | |
} | |
} | |
} | |
return head; | |
} | |
stack<Trie *> path; | |
int counts=0; | |
int findProper(Trie * head){ | |
if(head!=0){ | |
for(int i=0;i<26;i++){ | |
Trie *p=head->child[i]; | |
if(p){ | |
if(p->counts>5) | |
path.push(p); | |
else counts++; | |
} | |
} | |
} | |
while(!path.empty()){ | |
head=path.top(); | |
path.pop(); | |
findProper(head); | |
} | |
return counts; | |
} | |
int main(void) | |
{ | |
//freopen("input.txt","r",stdin); | |
int number=0; | |
cin>>number; | |
cout<<findProper(buid_tree(number)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment