poj2001 Shortest Prefixes ——字典树复习

April 19, 2013
POJ Data Structure

题目链接:http://poj.org/problem?id=2001 这道题目以前写过,复习一下字典树,再写一遍……


#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <set>
#include <map>
#include <vector>
#include <stack>
#include <queue>
#include <cmath>
#include <algorithm>
#define lson l, m, rt<<1
#define rson m+1, r, rt<<1|1
using namespace std;
typedef long long int LL;
const int MAXN =  0x3f3f3f3f;
const int  MIN =  -0x3f3f3f3f;
const double eps = 1e-9;
const int dir[8][2] = {{0,1},{1,0},{0,-1},{-1,0},{-1,1},
  {1,1},{1,-1},{-1,-1}};
char a[1000+10][30], base = 'a'; const int lo = 26;
typedef struct trie{
  int num; bool terminal;
  struct trie *son[lo];
}trie;
trie *newtrie(){
  trie *pnt = new trie;
  pnt->num = 1; pnt->terminal = false;
  for (int i = 0; i < lo; ++i) pnt->son[i] = NULL;
  return pnt;
}
void insert(char str[], trie *pnt, int len){
  trie *tem = pnt;
  for (int i= 0; i < len; ++i){
    if (tem->son[str[i]-base] != NULL){
      tem->son[str[i]-base]->num++;
    } else{
      tem->son[str[i]-base] = newtrie();
    } tem = tem->son[str[i]-base];
  }
  tem->terminal = true;
  return;
}
void find(char str[], trie *pnt, int len){
  trie *tem= pnt;
  for(int i = 0; i <len; ++i){
    if (tem->son[str[i]-base]->num == 1){
      printf("%c", str[i]); return;
    }
    printf("%c", str[i]);
    tem= tem->son[str[i]-base];
  }
  return;
}
int main(void){
#ifndef ONLINE_JUDGE
  freopen("2001.in", "r", stdin);
#endif
  int cnt = 0, i = 0; trie *pnt = newtrie();
  while (~scanf("%s", a[i])){
    insert(a[i], pnt, strlen(a[i])); i++;
  }
  for (int j = 0; j < i; ++j){
    printf("%s ", a[j]);
    find(a[j], pnt, strlen(a[j]));
    printf("\n");
  }

  return 0;
}

  写的过程中还是出现了一些错误,比如,在第60行,开始写成了 trie * pnt = new trie; 只新建了一个节点没有初始化,悲剧的是,竟然可以运行,样例可以过,但是OJ上RE……还有,初始化结构体中的num的时候,要初始化为1,而不是0.查找的时候,要看当前节点的子节点的num是不是1,如果是1,先输出再返回,函数结束,而不是看当前节点的num的值是不是1,这样会多输出一个字符。

comments powered by Disqus