POJ 2001-shortest Prefixes (trie tree)

Source: Internet
Author: User

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; }


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.