Zipper(DP)
Problem Description
Given three strings, you are to determine whether the third string can be formed by combining the characters in the first two strings. The first two strings can be mixed arbitrarily, but each must stay in its original order.
For example, consider forming “tcraete” from “cat” and “tree”:
String A: cat
String B: tree
String C: tcraete
As you can see, we can form the third string by alternating characters from the two strings. As a second example, consider forming “catrtee” from “cat” and “tree”:
String A: cat
String B: tree
String C: catrtee
Finally, notice that it is impossible to form “cttaree” from “cat” and “tree”.
Input
The first line of input contains a single positive integer from 1 through 1000. It represents the number of data sets to follow. The processing for each data set is identical. The data sets appear on the following lines, one data set per line. For each data set, the line of input consists of three strings, separated by a single space. All strings are composed of upper and lower case letters only. The length of the third string is always the sum of the lengths of the first two strings. The first two strings will have lengths between 1 and 200 characters, inclusive.
Output
For each data set, print: Data set n: yes if the third string can be formed from the first two, or Data set n: no if it cannot. Of course n should be replaced by the data set number. See the sample output below for an example.
Sample Input
3
cat tree tcraete
cat tree catrtee
cat tree cttaree
Sample Output
Data set 1: yes
Data set 2: yes
Data set 3: no
Source
Pacific Northwest 2004
zipper POJ 2192
这是一道很经典的题目,在算法竞赛宝典第二部的P572页有介绍。
这是很明显的LSC(最长公共字串)问题。其定义是:已知一个序列S,如果分别是两个或多个已知序列的子序列,且是所有符合此条件序列中最长的,则S称为已知序列的最长公共子序列。
- 用数组 Dp[x][y] 表示C前 x+y 个字符能否由 A 前 i 个与 B 前 j 个字符组成,前提条件是 Dp[x-1][y] 或 Dp[x][y-1] 为真。则求 Dp[x][y] 时会有 2 种情况:
- 第一种 1、如果 Dp[x-1][y] && C[x+y±1]==A[x] 成立;2、Dp[x][y-1] && C[x+y-1]==B[y] 成立。
- 第二种 1、满足时 Dp[x][y]=Dp[x-1][y]=1; 2、满足时 Dp[x][y]=Dp[x][y-1]+1,同时满足时则取最大的值。
#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
const int M = 201;
string s1, s2, s3;
int l1, l2, l3;
int a[M][M];
void dp(int cnt)
{
int x, y;
for (x = 1; x <= l1; x++)
a[x][0] = a[x - 1][0] + (s1[x - 1] == s3[x - 1]);
for (x = 1; x <= l2; x++)
a[0][x] = a[0][x - 1] + (s2[x - 1] == s3[x - 1]);
for (x = 1; x <= l1; x++)
for (y = 1; y <= l2; y++)
a[x][y] = max(a[x - 1][y] + (s1[x - 1] == s3[x + y - 1]), a[x][y - 1] + (s2[y - 1] == s3[x + y - 1]));
printf("Data set %d: ", cnt);
if (a[l1][l2] == l3)
printf("yes\n");
else
printf("no\n");
}
int main()
{
int n,i;
cin >> n;
for (i = 1; i <= n; i++)
{
cin >> s1 >> s2 >> s3;
l1 = s1.length();
l2 = s2.length();
l3 = s3.length();
dp(i);
}
return 0;
}