C - Erase Subsequences
You are given a string s. You can build new string p from s using the following operation no more than two times:
choose any subsequence si1,si2,…,sik where 1≤i1<i2<⋯<ik≤|s|;
erase the chosen subsequence from s (s can become empty);
concatenate chosen subsequence to the right of the string p (in other words, p=p+si1si2…sik).
Of course, initially the string p is empty.
For example, let s=ababcd. At first, let’s choose subsequence s1s4s5=abc — we will get s=bad and p=abc. At second, let’s choose s1s2=ba — we will get s=d and p=abcba. So we can build abcba from ababcd.
Can you build a given string t using the algorithm above?
Input
The first line contains the single integer T (1≤T≤100) — the number of test cases.
Next 2T lines contain test cases — two per test case. The first line contains string s consisting of lowercase Latin letters (1≤|s|≤400) — the initial string.
The second line contains string t consisting of lowercase Latin letters (1≤|t|≤|s|) — the string you’d like to build.
It’s guaranteed that the total length of strings s doesn’t exceed 400.
Output
Print T answers — one per test case. Print YES (case insensitive) if it’s possible to build t and NO (case insensitive) otherwise.
题意: 给出俩个字符串s,t,从s中找出俩个不相交的子序列s1和s2,使得s1+s2=t,如果存在这俩个字符串,则输出YES,否则输出NO。
题解: 定义a[i][j]为从s[i]开始第一个等于j的字符的位置,即任意i<=k<a[i][j],s[k]都不等于字符j,而且s[a[i][j]]=j。把输入的t分成前后俩部分t1和t2,dp[i][j]表示s[1]…s[dp[i][j]]能使t1[1]…t1[i]和t2[1]…t2[j]满足要求.。
dp[i][j]如何传递:dp[i][j]可以有dp[i-1][j]和dp[i][j-1]递推得来,取a[dp[i-1][j]+1][t1[i]-‘a’]和a[dp[i][j-1]+1][t2[j]-‘a’]的min,前者表示在dp[i-1][j]+1开始找到第一个等于t1[i]字符的位置,后者则是找t2[j]字符的位置。`
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define inf 0x3f3f3f3f
int dp[450][450],a[450][450];
char s[450],t[450];
int main(){
int c;
scanf("%d",&c);
while(c--){
scanf("%s %s",s+1,t+1);
int cnts=strlen(s+1);
int cntt=strlen(t+1);
memset(a,inf,sizeof(a));
for(int i=cnts;i>=1;i--){
for(int j=1;j<=i;j++){
a[j][s[i]-'a']=i;
}
}
int flag=0;
for(int i=0;i<=cntt;i++){
memset(dp,inf,sizeof(dp));
dp[0][0]=0;
for(int j=1;j<=i;j++){
int temp=dp[j-1][0]+1;
if(temp<=cnts)dp[j][0]=a[temp][t[j]-'a'];
else dp[j][0]=inf;
}
for(int j=1;j<=cntt-i;j++){
int temp=dp[0][j-1]+1;
if(temp<=cnts)dp[0][j]=a[temp][t[j+i]-'a'];
else dp[0][j]=inf;
}
for(int j=1;j<=i;j++){
for(int k=1;k<=cntt-i;k++){
int temp1=dp[j-1][k];
int temp2=dp[j][k-1];
if(temp1+1<=cnts)dp[j][k]=min(dp[j][k],a[temp1+1][t[j]-'a']);
if(temp2+1<=cnts)dp[j][k]=min(dp[j][k],a[temp2+1][t[k+i]-'a']);
//printf("dp[%d][%d]=%d\n",j,k,dp[j][k]);
}
}
if(dp[i][cntt-i]<=cnts){
flag=1;
break;
}
}
if(flag==1)printf("YES\n");
else printf("NO\n");
}
}