Codeforces 653B Bear and Compressing【DFS】

题目链接:

http://codeforces.com/problemset/problem/653/B

题意:

要求你构造一个长度为n的字符串使得通过使用m个操作,最终获得字符a。已知第i个操作将字符串中开头的字符串ai换成字符bi,长度减少1。问一共有多少种字符串构造方法。

分析:

直接dfs一下就好啦~~~

代码:

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
const int maxn = 105;
char a[maxn][2], b[maxn];
int n,q;
int dfs(int pos, int cnt)
{
    if(cnt <= 0) return 1;
    int ans = 0;
    for(int i= 0; i < q; i++){
        if(b[i] == a[pos][0]){
            ans += dfs(i, cnt - 1);
        }
    }
    return ans;
}
int main (void)
{
   cin>>n>>q;
   int pos;
   long long ans = 0;
   vector<int>v;
    for(int i = 0; i < q; i++){
        cin>>a[i][0]>>a[i][1]>>b[i];
        if(b[i] == 'a') v.push_back(i);
    }
    for(int i = 0; i < v.size(); i++){
        ans += dfs(v[i], n - 2);
    }
    cout<<ans<<endl;
}
原文地址:https://www.cnblogs.com/Tuesdayzz/p/5758719.html