Title: http://poj.org/problem?id=2001
Test instructions
At least 2 sets of strings, for each string, find the shortest prefix to recognize it, such as: Abbdef,abcdef. "AB" They are public prefixes, unrecognized, so the shortest recognition prefix is: ABB, ABC
Analysis:
Set up a section trie tree, the node holds a single letter, from the root node to the sub-leaf of a path, the occurrence of the word. When adding a word, the number of points in each node is +1, indicating that the prefix in total, and finally found the first value is 1 prefixes, can represent the shortest recognition prefix
Code:
#include <stdio.h> #include <iostream> #include <string.h> #include <string> #include < math.h> #include <algorithm> #include <queue> #include <stack> #include <vector> #include
<map> using namespace std;
#define MAX 1000+10 #define MIN-1E+10 #define INF 0x7f7f7f7f int t, n, M;
struct Trie {int id;//the prefix (the path from the current letter to the root node) occurrences Trie *child[26];//Next Letter Node Trie () {memset (child, 0, sizeof (child));
id = 0;
}} root;
void Insert (char str[])//Insert a word, update maintains a path {Trie *x = &root;
for (int i = 0; str[i]; i++)//Insert {if (x->child[str[i]-' a '] = = NULL)//The prefix does not appear {Trie *p = new Trie;
X->child[str[i]-' a '] = p;
x = P; } else x = x->child[str[i]-' a ']; The prefix already exists x->id++;
The prefix occurrences +1}} void Output (char str[])//output A word with the shortest identifier prefix {Trie *x = &root;
Char str1[30], len = 0;
for (int i = 0; str[i]; i++) {x = x->child[str[i]-' a '];//Search down prefix str1[len++] = str[i]; if (X->id = = 1)//Find the first occurrence of the number of 1 prefix, direct output break;
} Str1[len] = ' + ';
printf ("%s%s\n", str, STR1);
} int main () {int I, j, K;
Freopen ("A.txt", "R", stdin);
Char str[max][30];
for (n = 0; ~scanf ("%s", Str[n]), n++) {insert (str[n]);
} for (i = 0; i<n; i++) {output (str[i]);
} return 0; }