Usaco prefix trietree + dp

Source: Internet
Author: User

/* ID: kevin_s1prog: prefixlang: c ++ */# include <iostream> # include <cstdio> # include <string> # include <cstring> # include <vector> # include <map> # include <set> # include <algorithm> # include <cstdlib> # include <list> # include <cmath> using namespace STD; # define sigma_size 26 # define max_len 2000001 // Gobal variable ==== struct trie_node {trie_node * Next [sigma_size]; bool is_terminal; trie_node () {memset (next, 0, sizeof (n EXT); is_terminal = false ;}}; struct trie {trie_node * root; int size; int idx (char ch) {return ch-'A';} trie () {root = new trie_node (); size = 1;} void insert (string Str) {trie_node * cur = root; int Len = Str. length (); For (INT I = 0; I <Len; I ++) {int CH = idx (STR [I]); if (cur-> next [CH] = NULL) {cur-> next [CH] = new trie_node () ;}cur = cur-> next [CH];} cur-> is_terminal = true;} bool query (string Str) {trie_node * Cu R = root; int Len = Str. length (); For (INT I = 0; I <Len; I ++) {int CH = idx (STR [I]); if (cur-> next [CH] = NULL) {return false;} elsecur = cur-> next [CH];} If (cur-> is_terminal) return true; elsereturn false ;}}; int DP [max_len]; string S; // ====================================/// function ================== ================ int main () {freopen ("prefix. in "," r ", stdin); freopen (" prefix. out "," W ", stdout); trie prefix; string STR; char ch [201]; while (Scanf ("% s", CH) & strcmp (CH ,".")! = 0) {STR = CH; prefix. insert (STR);} Str. Clear (); int C; while (C = getchar ())! = EOF) {If (! Isspace (c) S = S + (char) C;} int Len = S. length (); memset (DP, 0, sizeof (DP); DP [Len] = 0; For (INT I = len-1; I> = 0; -- I) {for (Int J = 1; j <= 10 & (I + J-1) <Len; ++ J) {string sub = S. substr (I, j); If (prefix. query (sub) {If (DP [I + J] + j> DP [J]) DP [I] = DP [I + J] + J ;}}} cout <DP [0] <Endl; 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.