0001:#2797#:最短前缀

0001:#2797#:最短前缀_第1张图片 0001:#2797#:最短前缀_第2张图片 0001:#2797#:最短前缀_第3张图片
#include "iostream"
#include "string"
#include "deque"
#include "string.h"
using namespace std;
struct Node
{
	int  count;
	Node *child[26];
};
class Tree
{
private:
	Node *root;
public:
	Tree()
	{
		root=new Node;
		memset(root->child,NULL,sizeof(root->child));
		root->count=0;
	}
    void Insert(string str);
    void Find(string str);
};
void Tree::Find(string str)
{
   Node *p=root;
   const char *s=str.c_str();
   
   while(*s!='\0')
   { 
   int j=*s-'a';
   if(p->child[j]==NULL) return;
   cout<<*s;
   if(p->child[j]->count==1) break;
   p=p->child[j];
   s++;
   }
}
void Tree::Insert(string str)
{
  const char *s=str.c_str();
  Node *p=root;
  
  while(*s!='\0')
  {
   int t=*s-'a';
   if(p->child[t]==NULL)
   {
	   Node *q;
	   q=new Node;
	   memset(q->child,NULL,sizeof(q->child));
	   p->child[t]=q;
	   p->child[t]->count=1;
	   p=p->child[t]; 
   }
   else
   {   
	   p->child[t]->count++;
	   p=p->child[t];  
       
   }
   s++;
  }
 
}
int main()
{  
    deque<string> a;
    string word;
	Tree A; 
	//freopen("test.txt","r",stdin);
     while(cin>>word)
	{		  
		 a.push_back(word);
		 A.Insert(word);
	}
	for(int i=0;i<a.size();i++)
	{
		cout<<a[i]<<" ";
		A.Find(a[i]);
		cout<<endl;
	}
 
	return 0;
}

你可能感兴趣的:(0001:#2797#:最短前缀)