题目链接:点击打开链接
题意:
给定串a和串b。
1、把a中部分字母用空格代替。
2、把a的前导空格,后随空格去掉,把a中连续的空格变成一个空格
问能否和b一模一样。
若能输出一个a串,把被空格替代的字母用_表示。
意思其实可以当成每个单词都不能断。
所以我们用b串的每个单词在a串中找第一个匹配的子串。
边界处理麻烦了一点。
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <math.h>
#include <queue>
#include <set>
#include <algorithm>
using namespace std;
typedef int ll;
#define N 100010
int f[N];
void getFail(char *P, int len){
f[0] = f[1] = 0;
for(int i = 1; i < len; i++)
{
int j = f[i];
while(j && P[i]!=P[j]) j =f[j];
f[i+1] = P[i]==P[j]?j+1 : 0;
}
}
int find(char *T, int lent, char *P, int lenp){
getFail(P, lenp);
int j = 0;
for(int i = 0; i < lent; i++)
{
while(j && P[j] != T[i])j = f[j];
if(P[j]==T[i])j++;
if(j==lenp)return i;
}
return -1;
}
void put(char *x, int len){for(int i = 0; i < len; i++)printf("%c", x[i]);puts("");}
char T[N], P[N];
bool ok[N];
bool solve(){
memset(ok, 0, sizeof ok);
int lent = strlen(T), lenp = strlen(P);
int i, j, now = 0;
for(i = 0; i < lenp; i++){
for(j = i+1; j <= lenp; j++)
if(P[j]==0 || P[j]==' ')break;
int len = j - i;
// printf("len : %d now : %d\n", len, now);
// puts("P: "); put(P+i, len);
if(now + len > lent) return false;
// puts("T: "); put(T+now, lent-now);
int pos = find(T+now, lent - now, P+i, len);
if(pos == -1)return false;
pos += now;
// printf(" T[pos] = %c\n", T[pos]);
for(int j = pos - len+1; j <= pos; j++) ok[j] = 1;
now = pos + 2;
// printf(" T[now] = %c\n", T[now]);
i += len;
// printf("---P[i+1] : %c\n", P[i+1]); puts("");
}
for(int i = 0; T[i] ; i++)
if(ok[i] || T[i] == ' ')
printf("%c",T[i]);
else printf("_");
puts("");
return true;
}
int main(){
int i, j;
while(gets(T)){
gets(P);
if(solve()==false)puts("I HAVE FAILED!!!");
}
return 0;
}
/*
Preved to Medved
Preved Me
this is impossible
im possible
asdfasdfasdf
a a as f
ababac abaac
ab ac
*/