标签:style blog color os strong io for cti
Problem Statement |
|||||||||||||
We have three types of brackets: "()", "[]", and "{}". We are now interested in some special strings. A string is special if all the following conditions hold:
For example, the empty string is a special string: there are 0 pairs of brackets. The string "[]" is also a special string: there is one pair of matching brackets, they are in the proper order, and the string between them (which is the empty string) is a special string. The character ‘X‘ (uppercase x) occurs in expression at most five times; all other characters in expression are brackets of the types mentioned above. We want to change expression into a special string by changing each ‘X‘ into one of the brackets. (Different occurrences of ‘X‘ may be changed into different brackets.) Return "possible" (quotes for clarity) if we can do that, and "impossible" otherwise. |
|||||||||||||
Definition |
|||||||||||||
|
|||||||||||||
Limits |
|||||||||||||
|
|||||||||||||
Constraints |
|||||||||||||
- | expression will have between 1 and 50 characters, inclusive. | ||||||||||||
- | Each character in expression will be ‘(‘, ‘)‘, ‘[‘, ‘]‘, ‘{‘, ‘}‘ or ‘X‘. | ||||||||||||
- | There will be at most 5 occurences of ‘X‘ in expression. | ||||||||||||
Examples |
|||||||||||||
0) | |||||||||||||
|
|||||||||||||
1) | |||||||||||||
|
|||||||||||||
2) | |||||||||||||
|
|||||||||||||
3) | |||||||||||||
|
|||||||||||||
4) | |||||||||||||
|
题意:有三种括号 和 x,x能变成任意的括号,求能否通过变化x使得给的字符串符合括号匹配
一道中等DP题,先对每一种可能的匹配情况进行遍历,再对其松弛更新。
#include <iostream> #include <cstring> #include <cstdlib> #include <cmath> #include <cstdio> #include <vector> #define LL long long using namespace std; class BracketExpressions { public: int _max(int c, int d) { return c > d?c:d; } int match(char a, char b) { if(a==‘(‘ && b==‘)‘) return 1; if(a==‘{‘ && b==‘}‘) return 1; if(a==‘[‘ && b==‘]‘) return 1; if(a==‘X‘ &&(b==‘]‘||b==‘}‘||b==‘)‘)) return 1; if(b==‘X‘ && (a==‘[‘||a==‘{‘||a==‘(‘)) return 1; if(a==‘X‘ && b==‘X‘) return 1; return 0; } string ifPossible(string expression) { int i, j, k, g, len; int d[100][100]; string s = expression; len = s.size(); memset(d, 0, sizeof(d)); for(i = 0; i < len-1; i++) if(match(s[i], s[i+1])) d[i][i+1] = 1; for(k = 2; k < len; k++) { for(i = 0; i < len-k; i++) { j = i+k; if(match(s[i], s[j])) d[i][j] = d[i+1][j-1] + 1; for(g = 0; g < k; g++) d[i][j] = _max(d[i][i+g]+d[i+g+1][j], d[i][j]); } } if(2*d[0][len-1]!=len) return "impossible"; else return "possible"; } };
topcoder SRM628 div2 500(转),布布扣,bubuko.com
标签:style blog color os strong io for cti
原文地址:http://www.cnblogs.com/qiucz/p/3874899.html