CSP赛前集训 【表达式】

mac2025-08-29  8

表达式

题目描述:(暂不提供)

这道题放在第一题说明它很水。但是呢正是因为它很水但是细节较多所以我最后一个写这道题。结果呢后两题做太久了,最好做的 T 1 T1 T1反而没拿分。

这道题说实话就是要考虑多种情况。

考虑把它分成三层:原串,去空格后的串,压缩数字后的串。

对于原串你就判断一下有没有别的字符或者全是空格或者这就是一个空串。 这些都是不合法的。

对于去掉空格的串就判断一下连续空格两端连接的字符关系就好了。

由于数字连在一起就不是一个字符不好判断,所以我们干脆 O ( l e n ) O(len) O(len)的时间把这些连续的数字压缩成任意一个数字。

然后就两两判断一下就好了。

细节真的有点多。就这样吧,代码实现能力还是要提高啊。

#include <cstdio> #include <cstring> #include <iostream> using namespace std; const int N = 60; string s; int n,bz[N],f[N],len; int pd(char ch) { int p = 0; if(ch >= '0' && ch <= '9') p = 1; if(ch == '+' || ch == '-' || ch == '/' || ch == '*') p = 2; if(ch == '(') p = 3; if(ch == ')') p = 4; return p; } void no() { printf("No\n"); } void solve() { len = s.length(); int fg = 1,tot1 = 0,tot2 = 0; for(int i = 0;i < len; ++ i) { if(pd(s[i]) == 0 && s[i] != ' ') { no(); return; } if(s[i] != ' ') fg = 0; if(s[i] == '(') ++tot1; if(s[i] == ')') ++tot2; } if(tot1 != tot2) { no(); return; } if(fg) { no(); return; } if(!len) { no(); return; } //原串 char s1[N],s2[N]; int len1 = 0,len2 = 0; for(int i = 0;i < len; ++ i) if(s[i] == ' ' && i && i < len - 1) { char c1 = s[i - 1],c2; for(;s[i + 1] == ' ' && i < len - 1;) ++i; c2 = s[i + 1]; int x1 = pd(c1),x2 = pd(c2); if(x1 == 1 && x2 == 3) { no(); return; } if(x1 == 2 && x2 == 4) { no(); return; } if(x1 == 1 && x2 == 1) { no(); return; } } for(int i = 0;i < len; ++ i) if(s[i] != ' ') s1[++len1] = s[i]; //去空格后的串 int i = 1,j = 0; for(;i <= len1; ++i) if(pd(s1[i]) == 1) { for(;pd(s1[i + 1]) == 1 && i <= len1;) ++i; s2[++j] = '0'; } else s2[++j] = s1[i]; len2 = j; //压缩数字后的串 if(pd(s2[1]) == 2 || pd(s2[1]) == 4) { no(); return; } for(int i = 2;i <= len2; ++ i) { if(pd(s2[i]) == 3 && (pd(s2[i - 1]) == 4 || pd(s2[i - 1]) == 1)) { no(); return; } if(pd(s2[i]) == 4 && (pd(s2[i - 1]) == 3 || pd(s2[i - 1]) == 2)) { no(); return; } if(pd(s2[i]) == 1 && (pd(s2[i - 1]) == 4)) { no(); return; } if(pd(s2[i]) == 2 && (pd(s2[i - 1]) == 3 || pd(s2[i - 1]) == 2)) { no(); return; } if(pd(s2[i]) == 2 && (i == len2 || i == 1)) { no(); return; } } if(len2 == 1) { if(pd(s2[len2]) != 1) { no(); return; } } printf("Yes\n"); } int main() { freopen("expr.in","r",stdin); freopen("expr.out","w",stdout); scanf("%d",&n); ++n; getchar(); for(;--n;) getline(cin,s), solve(); fclose(stdin); fclose(stdout); return 0; }
最新回复(0)