CodeForces 762C Two strings

You are given two strings a and b. You have to remove the minimum possible number of consecutive (standing one after another) characters from string b in such a way that it becomes a subsequence of string a. It can happen that you will not need to remove any characters at all, or maybe you will have to remove all of the characters from b and make it empty.

Subsequence of string s is any such string that can be obtained by erasing zero or more characters (not necessarily consecutive) from string s.


题意是给了两个字符串a与b,求删掉b里的一个连续子序列,使得b变成a的子串(字串意为可以不连续)。

一直在想如何判断怎么判断删掉之后是子串呢。 想了很久之后想不出来之后我们还是考虑问题转换(如果关注我博客的话很多题都是喜欢提到问题转换)。我们可以对于a串与b串的前面进行匹配,pre[i]表示a的前第i位与b能匹配到的最大位置,所谓匹配就是第i位之前都能按顺序在b中找到相应的字符。sur[i] 便是对于第i位,对于其后面的最大匹配。

在求出pre和sur数组之后,便可以枚举s1的每一个位置,对于这个位置的上一个在前面和后面匹配到的最大位置(为什么是上一个,因为一个点不能被交两次),如果没有交集即都能分别在前后找到匹配,两者的差就是删掉序列的长度。

下附AC代码。

#include<iostream>
#include<string.h>
#include<stdio.h>
#define maxn 100005
using namespace std;
char s1[maxn],s2[maxn];
int pre[maxn],sur[maxn];
int main()
{
	scanf("%s%s",s1+1,s2+1);
	int l1=strlen(s1+1);
	int l2=strlen(s2+1);	
	int last=0;
	 
	for(int i=1;i<=l1;i++)  
    pre[i]=l2,sur[i]=1;  
    
	sur[l1+1]=l2+1;
	
	for(int i=1,j=1;i<=l1 && j<=l2; i++)
	{
		if(s1[i]==s2[j])
		{
			pre[i]=j;
			last=j;
			j++;
		}
		else 
		{
			pre[i]=last;
		}
	}
	last=l2+1;
	
	for(int i=l1,j=l2; i>=1 && j>=1 ;i--)
	{
		if(s1[i]==s2[j])
		{
			sur[i]=j;
			last=j;
			j--; 
		} 
		else
		{
			sur[i]=last;
		}
	}
	int ans=l2+1,l,r;
	
	for(int i=1;i<=l1+1;i++)
	{
		if(sur[i]-pre[i-1]>0)
		{
			if(ans>sur[i]-pre[i-1])
			{
				ans=sur[i]-pre[i-1];
				l=pre[i-1];
				r=sur[i];
			}
		}
	} 
	if(ans==l2+1)
	{
		cout<<"-"<<endl;
		return 0;
	}
	
	for(int i=1;i<=l2;i++)
	{
		if(i<=l || i>=r)
		{
			cout<<s2[i];
		}
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值