In the land of Hedonia the official language is Hedonian. A Hedonian professor had noticed that many of her students still did not master the syntax of Hedonian well. Tired of correcting the many syntactical mistakes, she decided to challenge the students and asked them to write a program that could check the syntactical correctness of any sentence they wrote. Similar to the nature of Hedonians, the syntax of Hedonian is also pleasantly simple. Here are the rules:
You are asked to write a program that checks if sentences satisfy the syntax rules given in Rule 0. - Rule 4.
The input consists of a number of sentences consisting only of characters p through z and N, C, D, E, and I. Each sentence is ended by a new-line character. The collection of sentences is terminated by the end-of-file character. If necessary, you may assume that each sentence has at most 256 characters and at least 1 character.
The output consists of the answers YES for each well-formed sentence and NO for each not-well-formed sentence. The answers are given in the same order as the sentences. Each answer is followed by a new-line character, and the list of answers is followed by an end-of-file character.
Cp Isz NIsz Cqpq
NO YES YES NO
uva271,这题在poj和hdu上也有,但是数据很弱,普通递归就可以过。但是在uva上需要使用记忆画搜索。另外这题也可以从后往前扫描一遍来判断是否符合要求。下面给出记忆画搜索的代码:
// // main.cpp // uva271 // // Created by Fangpin on 15/3/24. // Copyright (c) 2015年 FangPin. All rights reserved. // #include <iostream> #include <string> #include <cstring> using namespace std; char s[300]; int ok[300][300]; int judge(int l,int r){ if(ok[l][r]>=0) return ok[l][r]; if(r-l==1){ if('p'<=s[l] && s[l]<='z') return ok[l][r]=1; else return ok[l][r]=0; } if(s[l]=='N') return ok[l+1][r]=judge(l+1,r); else if(s[l]=='C' || s[l]=='D' || s[l]=='E' || s[l]=='I'){ bool flag=false; for(int i=l+2;i<=r-1;++i){ flag=( bool(ok[l+1][i]=judge(l+1,i)) )&&( bool(ok[i+1][r]=judge(i,r)) ); if(flag) break; } return flag; } else return 0; } int main(int argc, const char * argv[]) { // insert code here... while(~scanf("%s",s)){ memset(ok,-1,sizeof(ok)); if(judge(0,strlen(s))) cout<<"YES"<<endl; else cout<<"NO"<<endl; } return 0; }
原文:http://blog.csdn.net/fangpinlei/article/details/44596043