1. 程式人生 > 其它 >動態規劃||記憶化搜尋:Codeforces Round #597 (Div. 2)C. Constanze's Machine

動態規劃||記憶化搜尋:Codeforces Round #597 (Div. 2)C. Constanze's Machine

C. Constanze's Machine

傳送門:Problem - 1245C - Codeforces

題目:

 

 

 

 

題目大意:就是一個字串,m 會變成nn w會變成uu 問一個字串有原來有幾種可能。顯然如果出現m 或者 w直接輸出0 不可能,否則可以用數學歸納法:

n:1種

nn:2種

nnn:3種

nnnn:5種

nnnnn:8種 

所以發現本質是fib數列,也就是斐波那契數列,則可以On的時間複雜度尋找連續的n和u有幾個,然後記憶化搜尋剪枝,把每個搜尋結果*到ans上,ans初始化為1.

上程式碼:

 1 #include<iostream>
 2 #include<cstring>
 3
#include<cstdio> 4 #include<algorithm> 5 #include<map> 6 using namespace std; 7 string s; 8 long long dp[100000]; 9 const int mod = 1e9 + 7; 10 long long ans = 1; 11 int fib(int x) 12 { 13 if (dp[x])return dp[x]; 14 else 15 { 16 dp[x] = fib(x - 1) + fib(x - 2);
17 dp[x] %= mod; 18 return dp[x]; 19 } 20 } 21 int main() 22 { 23 cin >> s; 24 dp[1] = 1; 25 dp[2] = 2; 26 for (int i = 0; i < s.length(); ++i) 27 { 28 if (s[i] == 'u' || s[i] == 'n') 29 { 30 int x = 1; 31 int cnt = i;
32 i += 1; 33 while (i < s.length() && s[i] == s[cnt]) 34 { 35 x++; 36 i++; 37 } 38 ans *= fib(x); 39 ans %= mod; 40 i--; 41 } 42 if (s[i] == 'w' || s[i] == 'm') 43 { 44 cout << "0"; 45 return 0; 46 } 47 } 48 cout << ans; 49 return 0; 50 51 }