HihoCoder - 1110 - Regular Expression(區間dp )
阿新 • • 發佈:2018-12-26
Your task is to judge whether the input is a legal regular expression.
A regular expression is defined as follow:
1: 0 and 1 are both regular expressions.
2: If P and Q are regular expressions, PQ is a regular expression.
3: If P is a regular expression, § is a regular expression.
4: If P is a regular expression, P* is a regular expression.
5: If P and Q are regular expressions, P|Q is a regular expression.
Input
The input contains multiple testcases.
Each test case is a single line with a string not containing space.The length of the string is less than 100.
Output
For each testcase, print yes if the input is a regular expression, otherwise print no.
Sample Input
010101101*
(11|0*)*
)*111
Sample Output
yes
yes
no
題目連結
這是一個區間dp的題目,直接套用模板做的,只要區間內符合上面的條件便是符合表示式,一點一點的推出來。
#include <cstdio> #include <iostream> #include <algorithm> #include <cstring> using namespace std; int main() { char str[105]; int dp[105][105]; while(~scanf("%s", &str)) { int len = strlen(str); memset(dp, 0, sizeof(dp)); //0和1都是正則表示式,每一個區間佔一個格 for(int i = 0; i < len; i++) if(str[i] == '0' || str[i] == '1') dp[i][i] = 1; for(int l = 1; l < len; l++) for(int i = 0; i + l < len; i++) { int j = i + l; //兩側是括號,中間是正則表示式 if(str[i] == '(' && str[j] == ')' && dp[i + 1][j - 1]) dp[i][j] = 1; //前面部分是正則表示式,後面加* if(str[j] == '*' && dp[i][j - 1]) dp[i][j] = 1; for(int k = i; k < j; k++) { //乘法 if(dp[i][k] && dp[k + 1][j]) dp[i][j] = 1; // ‘|’運算,兩側都是正則表示式 if(dp[i][k] && str[k + 1] == '|' && dp[k + 2][j]) dp[i][j] = 1; } } if(dp[0][len - 1]) printf("yes\n"); else printf("no\n"); } return 0; }