鏈接:https://www.nowcoder.com/acm/contest/147/F
來源:牛客網
Niuniu is practicing typing.
Given n words, Niuniu want to input one of these. He wants to input (at the end) as few characters (without backspace) as possible,
to make at least one of the n words appears (as a suffix) in the text.
Given an operation sequence, Niuniu want to know the answer after every operation.
An operation might input a character or delete the last character.
輸入描述:
The first line contains one integer n. In the following n lines, each line contains a word. The last line contains the operation sequence. '-' means backspace, and will delete the last character he typed. He may backspace when there is no characters left, and nothing will happen. 1 <= n <= 4 The total length of n words <= 100000 The length of the operation sequence <= 100000 The words and the sequence only contains lower case letter.
輸出描述:
You should output L +1 integers, where L is the length of the operation sequence. The i-th(index from 0) is the minimum characters to achieve the goal, after the first i operations.
示例1
輸入
2 a bab baa-
輸出
1 1 0 0 0
這個題就可以先考慮只有一個模式串,在一個模式串下我們和操作串進行匹配,如果在模式串的i位置失配,那麼跳到模式串的Next[i] 的位置,如果沒有刪除操作,那麼就是一個kmp的複雜度,可是現在可以刪除,理論上加一個棧記錄與模式串匹配的位置,可以實現回退。可是會有這樣一個問題。
模式串 :aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
操作傳 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab-c-v-d-s-d-a-w-........
這樣以來,失配以後每次都要大量的跳轉,非常費時間。因此考慮記錄每個位置失配以後,每個字母對應的應該跳到的位置,
這樣一來,每一次跳轉肯定都是0(1)啦。
因爲所給的要匹配的字符串長度隨時變化,可以用變量cur記錄字符串裏有幾個字符,pos[cur] 記錄第cur個字符在模式串的匹配位置。那麼如果是刪除操作,只需要cur -- ,字符減少一個。如果是加字符,只需要cur++,pos[cur] 紀錄新加字母后模式串匹配的位置。
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5+666;
int n,Next[maxn],pre[maxn][26],Min[maxn],pos[maxn];
char s[5][maxn],sx[maxn];
void getNext(char s[])
{
int len = strlen(s),i = 0;
int k = -1;
Next[0] = -1;
while(i < len)
{
if(k == -1 || s[k] == s[i])
{
Next[++i] = ++k;
}
else
{
k = Next[k];
}
}
for(int i = 0; i <= len; i++)
{
for(int j = 0; j < 26; j++)
pre[i][j] = i == 0 ? 0 : pre[Next[i]][j];
if(i < len) pre[i][s[i]-'a'] = i+1;
}
}
void solve(char s[])
{
getNext(s);
int cur = 0;pos[0] = 0;
int len = strlen(s);
Min[0] = min(Min[0],len);
for(int i = 1; sx[i]; i++)
{
if(sx[i] == '-'){
cur = max(cur-1,0);
}else
{
pos[cur] = pre[pos[cur++]][sx[i]-'a'];
}
Min[i] = min(Min[i],len-pos[cur]);
}
}
int main()
{
scanf("%d",&n);
for(int i = 1; i <= n; i++) scanf("%s",s[i]);
scanf("%s",sx+1);
int len = strlen(sx+1)+1;
memset(Min,63,sizeof(Min));
for(int i = 1; i <= n; i++) solve(s[i]);
for(int i = 0; i < len; i++)
{
printf("%d\n",Min[i]);
}
return 0;
}