LA 3942 Remember the Word
生活随笔
收集整理的這篇文章主要介紹了
LA 3942 Remember the Word
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
(Remember the Word ,LA 3942)?
題目來源:https://vjudge.net/problem/UVALive-3942
題意:給定一個字符串S以及n個單詞,字符用這n個單詞進行拆分,輸出拆分的方案數。
思路:dp+字典樹
可以先將這n個單詞存儲于字典樹中,并記dp[i]:字符i開始的字符串的分解方案數量(即后綴S[i...end]),則動態轉移方程為dp[i]=sum{dp[i+len(x)] | 單詞x是S[i...end]的前綴}.
找S[i...end]的前綴可以在字典樹中查找。
AC代碼:
#define _CRT_SECURE_NO_DEPRECATE #include<iostream> #include<cmath> #include<algorithm> #include<cstring> #include<vector> #include<string> #include<iomanip> #include<map> #include<stack> #include<set> #include<queue> #include<cstdio> using namespace std; #define N_MAX 4000+5 #define L_MAX 4000*100+5 #define INF 0x3f3f3f3f #define MOD 20071027 typedef long long ll; int n; int dp[L_MAX]; int len[N_MAX]; char S[L_MAX]; struct Trie {int ch[L_MAX][26];int val[L_MAX];int sz;Trie() { sz = 1; memset(ch[0], 0, sizeof(ch[0])); }void init() { sz = 1; memset(ch[0], 0, sizeof(ch[0])); }int idx(char c) { return c - 'a'; }void insert(char*s, int v) {int u = 0, n = strlen(s);for (int i = 0; i < n; i++) {int c = idx(s[i]);if (!ch[u][c]) {memset(ch[sz], 0, sizeof(ch[sz]));val[sz] = 0;ch[u][c] = sz++;}u = ch[u][c];}val[u] = v;}//找長度為len的字符串s的前綴void find(char *s, int len, vector<int>&ans) {int u = 0;for (int i = 0; i < len; i++) {if (s[i] == '\0')break;int c = idx(s[i]);if (!ch[u][c]) break;u = ch[u][c];if (val[u] != 0)ans.push_back(val[u]);}} };Trie trie;//不要放到main()下int main() {int Case = 1;while (scanf("%s%d", S, &n) !=EOF) {memset(dp, 0, sizeof(dp));trie.init();for (int i = 1; i <= n; i++) {char x[100];scanf("%s", x);len[i] = strlen(x);trie.insert(x, i);//將單詞存入字典樹,單詞編號為i }int L = strlen(S);dp[L] = 1;for (int i = L - 1; i >= 0; i--) {vector<int>ans;//存儲單詞的編號trie.find(S + i, L - i, ans);for (int j = 0; j < ans.size(); j++) {dp[i] = (dp[i] + dp[i + len[ans[j]]]) % MOD;}}printf("Case %d: %d\n", Case++, dp[0]);}return 0; }?
轉載于:https://www.cnblogs.com/ZefengYao/p/8516576.html
總結
以上是生活随笔為你收集整理的LA 3942 Remember the Word的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: axure rp编辑html模板,Axu
- 下一篇: FFmpeg下载网络视频流