codeforces 653B
题意:
假
定
初
始
字
符
串
只
含
‘
a
’
—
‘
f
’
且
长
度
为
n
。
假定初始字符串只含‘a’—‘f’且长度为n。
假定初始字符串只含‘a’—‘f’且长度为n。
给
定
q
对
字
符
串
a
(
长
度
为
2
)
和
b
(
长
度
为
1
)
。
给定q对字符串a(长度为2)和b(长度为1)。
给定q对字符串a(长度为2)和b(长度为1)。
当
字
符
串
前
两
个
字
母
与
字
符
串
a
相
同
时
,
可
以
用
字
符
串
b
替
换
a
。
当字符串前两个字母与字符串a相同时,可以用字符串b替换a。
当字符串前两个字母与字符串a相同时,可以用字符串b替换a。
问
经
过
若
干
次
操
作
后
最
终
可
以
得
到
字
符
串
“
a
"
的
初
始
字
符
串
个
数
。
问经过若干次操作后最终可以得到字符串“a"的初始字符串个数。
问经过若干次操作后最终可以得到字符串“a"的初始字符串个数。
题解:
d p [ p o s ] [ p r e ] [ f l a g ] 表 示 处 理 到 第 p o s 位 , 第 一 位 为 字 符 ‘ a ’ + p r e 的 合 法 初 始 字 符 串 的 个 数 。 dp[pos][pre][flag]表示处理到第pos位,第一位为字符‘a’+pre的合法初始字符串的个数。 dp[pos][pre][flag]表示处理到第pos位,第一位为字符‘a’+pre的合法初始字符串的个数。
- 记 忆 化 搜 索 , d f s ( p o s − 1 , a [ i ] [ 0 ] − ′ a ′ , b [ i ] [ 0 ] − ′ a ′ = = p r e & & f l a g ) 记忆化搜索,dfs(pos-1, a[i][0]-'a', b[i][0]-'a' == pre \&\& flag) 记忆化搜索,dfs(pos−1,a[i][0]−′a′,b[i][0]−′a′==pre&&flag)
#include <bits\stdc++.h>
using namespace std;
int n, q;
string a[40], b[40];
int dp[10][10][2];
int dfs(int pos, int pre, int flag){
if(pos == 0){
return flag;
}
if(dp[pos][pre][flag] != -1){
return dp[pos][pre][flag];
}
int res = 0;
for(int i = 0 ; i < q ; i++){
res += dfs(pos-1, a[i][0]-'a', b[i][0]-'a' == pre && flag);
}
dp[pos][pre][flag] = res;
return res;
}
int main() {
cin >> n >> q;
memset(dp, -1, sizeof(dp));
for(int i = 0 ; i < q ; i++){
cin >> a[i] >> b[i];
}
cout << dfs(n-1, 0, 1) << endl;
return 0;
}