IndiaHacks 2016 - Online Edition (Div. 1 + Div. 2) B. Bear and Compressing 暴力

B. Bear and Compressing

题目连接:

http://www.codeforces.com/contest/653/problem/B

Description

Limak is a little polar bear. Polar bears hate long strings and thus they like to compress them. You should also know that Limak is so young that he knows only first six letters of the English alphabet: 'a', 'b', 'c', 'd', 'e' and 'f'.

You are given a set of q possible operations. Limak can perform them in any order, any operation may be applied any number of times. The i-th operation is described by a string ai of length two and a string bi of length one. No two of q possible operations have the same string ai.

When Limak has a string s he can perform the i-th operation on s if the first two letters of s match a two-letter string ai. Performing the i-th operation removes first two letters of s and inserts there a string bi. See the notes section for further clarification.

You may note that performing an operation decreases the length of a string s exactly by 1. Also, for some sets of operations there may be a string that cannot be compressed any further, because the first two letters don't match any ai.

Limak wants to start with a string of length n and perform n - 1 operations to finally get a one-letter string "a". In how many ways can he choose the starting string to be able to get "a"? Remember that Limak can use only letters he knows.

Input

The first line contains two integers n and q (2 ≤ n ≤ 6, 1 ≤ q ≤ 36) — the length of the initial string and the number of available operations.

The next q lines describe the possible operations. The i-th of them contains two strings ai and bi (|ai| = 2, |bi| = 1). It's guaranteed that ai ≠ aj for i ≠ j and that all ai and bi consist of only first six lowercase English letters.

Output

Print the number of strings of length n that Limak will be able to transform to string "a" by applying only operations given in the input.

Sample Input

3 5

ab a

cc c

ca a

ee c

ff d

Sample Output

4

Hint

题意

你需要构造一个长度为n的串,使得经过n-1次变换之后得到a

现在你可以进行m种变换

变换描述如下:如果首两个字符为b1b2,那么你可以变成c

问你一共有多少种构造方案。

题解:

数据范围n=6,所以直接dfs就好了,数据范围很小的。

代码

#include<bits/stdc++.h>
using namespace std;
int n,q;
int x[50],y[50],z[50];
vector<int>ans;
int Ans=0;
void dfs(int x1)
{
if(x1==n)
{
int flag = 0;
int now = ans[0];
for(int i=1;i<ans.size();i++)
{
int flag2 = 1;
for(int j=0;j<q;j++)
{
if(now==x[j]&&ans[i]==y[j])
{
flag2 = 0;
now = z[j];
break;
}
}
if(flag2)
return;
}
if(now==0)Ans++;
return;
}
for(int i=0;i<6;i++)
{
ans.push_back(i);
dfs(x1+1);
ans.pop_back();
}
}
int main()
{
scanf("%d%d",&n,&q);
for(int i=0;i<q;i++)
{
string x1,y1;
cin>>x1>>y1;
x[i]=(int)(x1[0]-'a');
y[i]=(int)(x1[1]-'a');
z[i]=(int)(y1[0]-'a');
}
dfs(0);
cout<<Ans<<endl;
}
上一篇:做题记录 To 2019.2.13


下一篇:grep: /usr/include/php/main/php.h: No such file or directory