CF653B 1300

题意

长度为n的字符串(字符串中只有abcdef共6种字母),有q种压缩方式,可以将字符串的前两个字符压成1个字符,求凭借这q种压缩方式,有几种长度为n的字符串最终能被压缩成字符'a'.
输入格式:
第一行输入两个整数n(2<=n<=6)和q(1<=q<=36),代表压缩前字符串的长度以及压缩方式的种类数
接下来q行,每行两个字符串,长度分别为2和1,只有abcdef共6种字母,代表前面的字符串可以压缩成后面的字符串
输出格式:
输出长度为n的符合条件的字符串种类数
说明:
在第一个样例中,符合条件的长度为3的字符串有4中,“abb”,“cab”,“cca”,“eea”
“abb” —> “ab” —> “a”
“cab” —> “ab” —> “a”
“cca” —> “ca” —> “a”
“eea” —> “ca” —> “a”

解析

写的时候用了麻烦的做法,从a开始推
官方题解是说枚举6^n次生成所有,然后每个判断

代码

#include <bits/stdc++.h>
using namespace std;
int n,q;
string s;
map<char,vector<string> > mp;
map<string,bool> vis;
int res;
int ans = 0;
void dfs(string now,int cnt){
	// ans++;
	// if(ans == 50) exit(0);
	// cout << now << " " << cnt << endl;
	if(cnt == n){
		if(!vis.count(now)){
			vis[now] = true;
			res++;
		}
		return;
	}
	char c = now[0];
	for(auto &t : mp[c]){
		dfs(t + now.substr(1),cnt+1);
	}
}

int main(){
	cin >> n >> q;
	while(q--){
		string s;
		char c;
		cin >> s >> c;
		mp[c].push_back(s);
	}

	dfs(string(1,'a'),1);

	cout << res;
	return 0;
}
posted @   Isaac233  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示