天天看点

codeforce_314D Sereja and Periods (动态规划)

Description

Let's introduce the designation 

codeforce_314D Sereja and Periods (动态规划)

, where x is a string, n is a positive integer and operation " + " is the string concatenation operation. For example, [abc, 2] = abcabc.

We'll say that string scan be obtained from string t, if we can remove some characters from string t and obtain string s. For example, strings ab and aсba can be obtained from string xacbac, and strings bx and aaa cannot be obtained from it.

Sereja has two strings, w = [a, b] and q = [c, d]. He wants to find such maximum integer p(p > 0), that [q, p] can be obtained from string w.

Input

The first line contains two integers b, d(1 ≤ b, d ≤ 107). The second line contains string a. The third line contains string c. The given strings are not empty and consist of lowercase English letters. Their lengths do not exceed 100.

Output

In a single line print an integer — the largest number p. If the required value of p doesn't exist, print 0.

Sample Input

Input

10 3
abab
bab
      

Output

3      

【思路】从串1中查找串2,但是串1和串2都是>=1个,这道题刚开始一看就是一个字符串匹配问题,但是写了以后一提交发现超时了,原来数据量很大,肯定超时,所以就用dp做了,不过技巧性很重。

【转载】http://www.cnblogs.com/A-way/archive/2013/06/08/3127694.html

【代码】:

#include<iostream>
#include<string>
#include<cstdio>
using namespace std;
const int N=110;

int main()
{
    int m,n,ans[N],node[N];
    int now;
    string str1,str2;
    while(~scanf("%d%d",&m,&n))
    {
        cin>>str1>>str2;
        for(int i=0;i<str2.length();i++)//2串中以各个字符开头的字符串在1串中出现的次数
        {
            int now=i;
            for(int j=0;j<str1.length();j++)
            {
                if(str1[j]==str2[now%str2.length()]) now++;
            }
            node[i]=now/str2.length();
            ans[i]=now%str2.length();
        }
        int anss=0;
        now=0;
        for(int i=0;i<m;i++)
        {
            anss+=node[now];
            now=ans[now];
        }
        printf("%d\n",anss/n);
    }
    return 0;
}
           

ps:多理解理解!!