View Code of Problem 2201

#include <iostream>
#include<cstring>
#include<cstdio>

using namespace std;
//字典树
const int M=1000000;
char word[100000][11];
int wp;
struct node
{
   int next[26];
    int value;
    bool end;
}tree[M];

int pi=1;

void insert(char * keyword,int value)  //建树
{
    int index,p,i;
    for(i=p=0;keyword[i];i++)
    {
        index=keyword[i]-'a';   //
         if(tree[p].next[index]==0)     //
             tree[p].next[index]=pi++;

           p=tree[p].next[index];
    }
    tree[p].value=value;
     tree[p].end=1;
}

  bool query(char * keyword,int& value)
  {
        int index,p,i;
        for(i=p=0;keyword[i];i++)
        {
            index=keyword[i]-'a';
             if(tree[p].next[index]==0)
                  return 0;
                p=tree[p].next[index];
        }
        if(tree[p].end)
        {
            value=tree[p].value;
            return 1;
        }
        return 0;
  }

  int main()
  {
      char s1[15],s2[15],s[30];
       int i,value;
        while(gets(s))
        {
            if(!strlen(s))  
            break;

            for(i=0;i<strlen(s);i++)
            {
                if(s[i]==' ')   
                    break;
            }
            strncpy(s1,s,i);  
            s1[i]=0;
            strcpy(s2,s+i+1);   
            strcpy(word[wp],s1); 
               insert(s2,wp++);  
        }
          while(scanf("%s",s)!=EOF)
          {
              if(query(s,value))     
                 printf("%s\n",word[value]);
               else
                printf("eh\n");  
          }
       return 0;
  }

Double click to view unformatted code.


Back to problem 2201