poj 2001 Shortest Prefixes(trie树)

小记:1A


思路:插入时对每个遇到的字符增加个标记,出现一次就增加1,那么最后只有出现一次的就是最短前缀

查找时,碰到1的就将该串字符头至标记为1的字符输出即可


代码:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <map>
#include <set>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>

using namespace std;

#define mst(a,b) memset(a,b,sizeof(a))
#define eps 10e-8

const int MAX_ = 1010;
const int MAX = 26;
const int N = 500010;
const int INF = (1<<30);

typedef struct Node{
    int isStr;
    int num;
    struct Node *next[MAX];

    Node():isStr(-1),num(0){
        memset(next, NULL, sizeof(next));
    }
    ~Node(){
        for(int i = 0;i < MAX; ++i)
            if(next[i] != NULL)
                delete next[i];
    }
}TrieNode,*Trie;

Trie root , root1;
char s[MAX],  ss[MAX_][MAX];
int n, m;

void Insert(char *s){

    TrieNode *p;
    p = root;

    while(*s){
        if(p ->next[*s-'a'] == NULL){
            p ->next[*s-'a'] = new TrieNode;
        }
        p = p ->next[*s-'a'];
        p->num ++;
        s++;
    }
    p->isStr = 1;
}

void find(char *s){
    int i = 0;
    TrieNode *p;
    p=root;
    //printf("%s ", s);
    while(*(s+i)){
        if(p->next[*(s+i)-'a'] == NULL)return ;
        p = p->next[*(s+i)-'a'];
        ++i;
        if(p->num == 1){
            break;
        }
    }
    for(int j = 0; j < i; ++j){
        printf("%c",s[j]);
    }
    putchar('\n');
}


int main() {

    //freopen("f:\\in.txt", "r", stdin);

    int ans, cnt1, cnt2, len, T, k, inj, st, et, cnt;
    bool flag;
    flag = true;
    root = new TrieNode;cnt = 0;
    //ans = 0;flag = false;cnt = 0;
    while(scanf("%s", s) != EOF){
        strcpy(ss[cnt++], s);
        Insert(s);
    }
    for(int i = 0; i < cnt; ++i){
        printf("%s ",ss[i]);
        find(ss[i]);
    }
    delete root;

}


你可能感兴趣的:(poj 2001 Shortest Prefixes(trie树))