首页 > 其他 > 详细

hdu1501 记忆化搜索。。。

时间:2016-04-17 00:46:57      阅读:242      评论:0      收藏:0      [点我收藏+]
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
首先说关于字符串匹配寻找的基本思想  将 a b两个数字的位数依次和c中的比较  如果匹配合适的话 a/b 以及c的坐标前移一位 搜索的终点为字符串的结尾‘\0’
这里用的dfs的参数有三个  分别为a b c三个数组的坐标(当a b的某位和c相同的时候 便出现了分支 也正是由于分支的存在 所以标记数组就可以出现用来剪枝啦)
由于到达坐标 i j(由于c数组的长度为 a b之和 所以k没有必要作为参数 一个二维数组就可以搞定了) 的情况有很多种 我们的目标是去匹配字符  当坐标为i j的时候
a b c剩下的字符都是一样的 所以不论怎么匹配到 i j 情况都是一样的 为了避免超时  这里就可以用一个标记数组进行记忆搜索啦
贴上代码
#include<stdio.h>
#include<iostream>
#include<string.h>
using namespace std;
string a,b,c;
int vis[501][500],flag;
void dfs(int i,int j,int k)
{
 if(vis[i][j]) return;// 对标记过的次数直接忽视
 vis[i][j]=1; // 标记
 if(c[k]==‘\0‘)
 {
   flag=1;
   return; 
 }
 if(a[i]==c[k]&&b[j]==c[k])
 {
  dfs(i+1,j,k+1);
  dfs(i,j+1,k+1);
 }else if(a[i]==c[k]&&b[j]!=c[k])
 {
  dfs(i+1,j,k+1);
 }else if(a[i]!=c[k]&&b[j]==c[k])
 {
  dfs(i,j+1,k+1);
 }
}
int main()
{
 int n,i;
    scanf("%d",&n);
    for(i=1;i<=n;i++)
    {
     cin>>a>>b>>c;
     flag=0;
     memset(vis,0,sizeof(vis));
        dfs(0,0,0);
        printf("Data set %d: ",i);
  if(flag==1) cout<<"yes"<<endl;
  else cout<<"no"<<endl;     
    }
 return 0;
}

hdu1501 记忆化搜索。。。

原文:http://www.cnblogs.com/z1141000271/p/5399852.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!