BestCoder 1st Anniversary B.Hidden String DFS

B. Hidden String

Time Limit: 1 Sec

Memory Limit: 256 MB

题目连接

http://bestcoder.hdu.edu.cn/contests/contest_chineseproblem.php?cid=610&pid=1002

Description

今天是BestCoder一周年纪念日. 比赛管理员Soda有一个长度为n的字符串s. 他想要知道能否找到s的三个互不相交的子串s[l1..r1], s[l2..r2], s[l3..r3]满足下列条件:

  1. 1l1r1<l2r2<l3r3n

  2. s[l1..r1], s[l2..r2], s[l3..r3]依次连接之后得到字符串"anniversary".

Input

输入有多组数据. 第一行有一个整数T (1T100), 表示测试数据组数. 然后对于每组数据:

一行包含一个仅含小写字母的字符串s (1|s|100).

Output

对于每组数据, 如果Soda可以找到这样三个子串, 输出"YES", 否则输出"NO".

Sample Input

2
annivddfdersewwefary
nniversarya

Sample Output

YES
NO

HINT

题意

题解:

DFS

代码

 1 #include <cstdio>
 2 #include <cmath>
 3 #include <cstring>
 4 #include <ctime>
 5 #include <iostream>
 6 #include <algorithm>
 7 #include <set>
 8 #include <vector>
 9 #include <sstream>
10 #include <queue>
11 #include <typeinfo>
12 #include <fstream>
13 #include <map>
14 #include <stack>
15 typedef __int64 ll;
16 using namespace std;
17 
18 typedef __int64 ll;
19 const int inf = (int)1E9+10;
20 inline ll read()
21 {
22     ll x=0,f=1;
23     char ch=getchar();
24     while(ch<'0'||ch>'9')
25     {
26         if(ch=='-')f=-1;
27         ch=getchar();
28     }
29     while(ch>='0'&&ch<='9')
30     {
31         x=x*10+ch-'0';
32         ch=getchar();
33     }
34     return x*f;
35 }
36 
37 //*******************************
38 
39 
40 int T;
41 char s[1111];
42 char s1[] = "anniversary";
43 bool dfs(int num,int k,int i)
44 {
45     if(num >= 3) return 0;
46     while(s[k] != '')
47     {
48         if(s[k] == s1[i])
49         {
50             k++;
51             i++;
52             if(dfs(num+1,k,i)) return true;
53             if(s1[i] == '')return true;
54         }
55         else
56         {
57             break;
58         }
59     }
60     for(; s[k] != ''; ++k)
61     {
62         if(s[k] == s1[i])
63         {
64             if(dfs(num+1,k,i)) return true;
65         }
66     }
67     return false;
68 }
69 int main()
70 {
71     cin>>T;
72     while(T--)
73     {
74         scanf("%s",s);
75         int flag=0;
76         for(int i=0; s[i]!=''; ++i)
77         {
78             if(s[i]=='a')
79             {
80                 flag=dfs(0,i,0);
81                 if(flag) break;
82             }
83         }
84         if(flag) printf("YES
");
85         else printf("NO
");
86     }
87     return 0;
88 }
原文地址:https://www.cnblogs.com/zxhl/p/4676841.html