链接:https://vjudge.net/problem/HDU-1501
题意:
给定3个字符串,在不改变原来顺序上能否用第一个和第二个组成第三个。
思路:
dp。dp[i][j]表示可以用第一个字符串前i位和第二个字符串前j位,组成第三个字符串前i+j位。
两重循环。
考虑每一次ij,当dp[i-1][j]为1 && a[i-1] == c[i+j-1] 时, dp[i][j] = 1;j同理。
DFS。Vis[i][j]记录到达过此种状态不用考虑。
代码:
dp
#include <iostream>
#include <memory.h>
#include <vector>
#include <map>
#include <algorithm>
#include <cstdio>
#include <math.h>
#include <queue>
#include <string>
#include <stack>
#include <iterator>
#include <stdlib.h>
#include <time.h>
#include <assert.h>
using namespace std;
typedef long long LL;
const int MAXN = 1000 + 10;
int dp[MAXN][MAXN];
int main()
{
int t, cnt = 0;
string a, b, c;
cin >> t;
while (t--)
{
cin >> a >> b >> c;
memset(dp, 0, sizeof(dp));
/*
for (int i = 1;i <= a.length();i++)
dp[i][0] = (a[i-1] == c[i-1]);
for (int i = 1;i <= b.length();i++)
dp[0][i] = (b[i-1] == c[i-1]);
*/
if (a[0] == c[0])
dp[1][0] = 1;
if (b[0] == c[0])
dp[0][1] = 1;
for (int i = 0;i <= a.length();i++)
{
for (int j = 0;j <= b.length();j++)
{
if (dp[i][j-1] && b[j-1]==c[i+j-1])
dp[i][j] = 1;
if (dp[i-1][j] && a[i-1]==c[i+j-1])
dp[i][j] = 1;
}
}
if (dp[a.length()][b.length()])
printf("Data set %d: yes\n",++cnt);
else
printf("Data set %d: no\n",++cnt);
}
return 0;
}
DFS
#include <iostream>
#include <memory.h>
#include <vector>
#include <map>
#include <algorithm>
#include <cstdio>
#include <math.h>
#include <queue>
#include <string>
#include <stack>
#include <iterator>
#include <stdlib.h>
#include <time.h>
#include <assert.h>
using namespace std;
typedef long long LL;
const int MAXN = 1000 + 10;
int Vis[MAXN][MAXN];
bool flag = false;
string a, b, c;
void Dfs(int x, int y, int z)
{
if (z == c.length())
{
flag = true;
return ;
}
if (Vis[x][y])
return;
Vis[x][y] = 1;
if (a[x] == c[z])
Dfs(x+1, y, z+1);
if (b[y] == c[z])
Dfs(x, y+1, z+1);
}
int main()
{
int t, cnt = 0;
cin >> t;
while (t--)
{
cin >> a >> b >> c;
memset(Vis, 0, sizeof(Vis));
flag = false;
Dfs(0, 0, 0);
if (flag)
printf("Data set %d: yes\n",++cnt);
else
printf("Data set %d: no\n",++cnt);
}
return 0;
}