UVA 1401-remember the Word (TRIE+DP)

Source: Internet
Author: User

UVA 1401-remember the Word

[Topic link]

Test instructions: given some words. and a long string. Ask this long string split into existing words, can split into several ways

Train of thought: Trie, the word is built Trie first. Then the DP. Dp[i] Indicates a case that begins with I, and then each state simply finds the corresponding I-beginning word on the trie tree, then dp[i] = Sum{dp[i + len]} for state transfer to

Code:

#include <cstdio> #include <cstring>const int MOD = 20071027;const int N = 300005;char Str[n], Word[105];int S,    sz;struct Node {int next[26], Val;} node[n];void Insert (char *str) {int len = strlen (str);    int u = 0; for (int i = 0; i < len; i++) {int v = str[i]-' a '; if (node[u].next[v]) U = node[u].next[v];else {node[u].next[    V] = sz++;    U = node[u].next[v];    Node[u].val = 0;    memset (node[u].next, 0, sizeof (node[u].next));} } node[u].val = 1;}    void init () {sz = 1;    memset (node[0].next, 0, sizeof (node[0].next)); Node[0].val = 0;}    int dp[n];void find (int i) {int u = 0;    Dp[i] = 0;       for (int j = i; str[j]; j + +) {int v = str[j]-' a '; if (!node[u].next[v]) return;    U = node[u].next[v];if (node[u].val) dp[i] = (Dp[i] + dp[j + 1])% MOD;    }}int Main () {int cas = 0;    while (~SCANF ("%s", str)) {scanf ("%d", &s), Init (); and while (s--) {scanf ("%s", word); Insert (Word);} int len = strlen (str);DP [len] = 1;for (int i = len -1; I >= 0;    i--) Find (i);p rintf ("Case%d:%d\n", ++cas, dp[0]); } return 0;}


UVA 1401-remember the Word (TRIE+DP)

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.