hdoj 5311 Hidden String 【dfs(递归)】【周赛】

18 篇文章 0 订阅

Hidden String

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 1691    Accepted Submission(s): 597


Problem Description
Today is the 1st anniversary of BestCoder. Soda, the contest manager, gets a string  s  of length  n . He wants to find three nonoverlapping substrings  s[l1..r1] s[l2..r2] s[l3..r3]  that:

1.  1l1r1<l2r2<l3r3n

2. The concatenation of  s[l1..r1] s[l2..r2] s[l3..r3]  is "anniversary".
 

Input
There are multiple test cases. The first line of input contains an integer  T   (1T100) , indicating the number of test cases. For each test case:

There's a line containing a string  s   (1|s|100)  consisting of lowercase English letters.
 

Output
For each test case, output "YES" (without the quotes) if Soda can find such thress substrings, otherwise output "NO" (without the quotes).
 

Sample Input
  
  
2 annivddfdersewwefary nniversarya
 

Sample Output
  
  
YES NO
 

Source
 

Recommend
hujie   |   We have carefully selected several similar problems for you:   5594  5593  5592  5591  5590 
 

Statistic |  Submit |  Discuss |  Note



思路:
这道题用的是递归的方法,因为如果你用遍历的方法的时候如果输入这个样例就会出错:
annianniverannisaannrianniannianniversary
的时候就会出错!因为每次都尽可能多的将字符存到前面的子串里面,最终前面有很多和主串相同的字符,但是最后有一个整的,

最终会使你的串的个数超过3,所以不能这样查找!应该从第一个字符开始进行找和b数组(也就是主串里面的字符相同的字符)找到之后继续匹配,遍历一遍所有的起点与b[0]相同的字符,来查找有没有anniversary!

//因为第一个起点的位置不确定有可能有多个,同样第二个起点的位置也
//不确定,第三个起点的位置也不确定所以就要采用递归的思想来查找所有的 
//可能的起点所能造成的结果中有没有满足题意的结果! 

AC代码:
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
char a[105];
char b[20]="anniversary";
int len;
int flag;
void dfs(int p1,int p2,int cnt)
{
	if(cnt>3)
	{
		return;
	}
	if(p2>=11)
	{
		flag=1;
		return;
	}
	for(int i=p1;i<len;i++)
	{
		int x=i,y=p2;
		while(a[x]==b[y])
			x++,y++;
		dfs(x+1,y,cnt+1);//不相等,那么就继续往后找下一个区间 
	} 
}
int main()
{
	int T;
	scanf("%d",&T);
	while(T--)
	{
		flag=0;
		scanf("%s",a);
		len=strlen(a);
		dfs(0,0,0);
		if(flag)
			printf("YES\n");
		else
			printf("NO\n");
	}
	return 0;
}


附带错误代码:

#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
char a[105];
char b[20]="anniversary";
int main()
{
	int T;
	scanf("%d",&T);
	while(T--)
	{
		scanf("%s",a);
		int len=strlen(a),t=0,cnt=0,flag=0;
		for(int i=0;i<len;i++)
		{
			if(a[i]==b[t])
			{
				t++;
				if(flag==0)//刚开始匹配成功 
				{
					flag=1;
					cnt++;
				}
			}
			else
			{
				flag=0;
			}
		}
		if(cnt<=3&&t==11)
		{
			printf("YES\n");
		}
		else
		{
			printf("NO\n");
		}
	}
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值