3643-Keep Deleting
Time Limit:2000MS Memory Limit:65536KB
Description
Assume that string A is the substring of string B if and only if we can find A in B, now we have a string A and another string B, your task is to find a A in B from B’s left side to B’s right side, and delete it from B till A is not a substring of B, then output the number of times you do the delete.
There are only letters(A-Z, a-z) in string A and B.
Input
This problem contains multiple test cases. Each case contains two line, the first line is string A, the second line is string B, the length of A is less than 256, the length of B is less than 512000.
Output
Print exactly one line with the number of times you do the delete for each test case.
Sample Input
abcd
abcabcddabcdababcdcd
Sample Output
5
题目链接:ZOJ-3643
题目大意:给出一个sub字串,s原串,每次操作从s中删去一个sub。一直删到没有为止。
eg:
abcabcddabcdababcdcd delete=0 abcdabcdababcdcd delete=1 abcdababcdcd delete=2 ababcdcd delete=3 abcd delete=4 delete=5
题目思路: 设置一个数组pre,记录当前字母前一个字母的下标
初始:
删除一个abcd之后:
以下是代码:
#include<iostream>
#include<cmath>
#include<cstring>
#include<string>
#include<cstdio>
#include<vector>
#include<algorithm>
#include<map>
using namespace std;
int pre[512005];
int main()
{
string s,sub;
while(cin >> sub >> s)
{
for (int i = 1; i < s.size(); i++)
{
pre[i] = i - 1;
}
char alp = sub[sub.size() - 1];
int ans = 0;
for (int i = sub.size() - 1; i < s.size(); i++)
{
if (s[i] == alp) //遍历是否为终点
{
int flag = 0;
int last = 0;
for (int j = i,k = 0; k < sub.size() ; j = pre[j],k++)
{
if (j < 0)
{
flag = 1;
break;
}
if (s[j] != sub[sub.size() - k - 1])
{
flag = 1;
}
last = j;
}
if (!flag)
{
pre[i + 1] = last - 1;
ans++;
}
}
}
cout << ans << endl;
}
return 0;
}