一道单纯的模拟题,仔细想一下有很多种的情况,我是用两个数组,一个是记录 ++i 和 --i 前缀时候的更新后 i 的值,另一个记录 前缀和后缀 更新后的值。还有就是输入的时候允许有空格 a + + 等价于 a++。我就WA在了这里。题意没弄明白。一直WA到死。。。
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <iostream>
#include <string>
using namespace std;
int before_al[30], after_al[30], value, opt[30], len, rlen, tmp;
char str[120];
string res;
int main ( ) {
while ( getline ( cin, res ) ) {
printf ( "Expression: ");
cout << res << endl;
value = tmp = 0;
for ( int i = 0; i < res.size ( ); ++i )
if ( islower ( res[i] ) || res[i] == '+' || res[i] == '-' ) str[tmp++] = res[i];
len = tmp;
for ( int i = 0; i < 26; ++i )
before_al[i] = after_al[i] = i + 1, opt[i] = 0;
for ( int i = 0; i < len; ++i ) {
if ( islower ( str[i] ) ) opt[str[i] - 'a'] = 1;
if ( str[i] == '+' && str[i + 1] == '+' && islower ( str[i + 2] ) ) after_al[str[i + 2] - 'a']++, before_al[str[i + 2] - 'a']++, str[i] = 'A', str[i + 1] = 'A', opt[str[i + 2] - 'a'] = 1;
if ( str[i] == '-' && str[i + 1] == '-' && islower ( str[i + 2] ) ) after_al[str[i + 2] - 'a']--, before_al[str[i + 2] - 'a']--, str[i] = 'A', str[i + 1] = 'A', opt[str[i + 2] - 'a'] = 1;
if ( islower ( str[i] ) && str[i + 1] == '+' && str[i + 2] == '+' ) after_al[str[i] - 'a']++, str[i + 1] = 'A', str[i + 2] = 'A', opt[str[i] - 'a'] = 1;
if ( islower ( str[i] ) && str[i + 1] == '-' && str[i + 2] == '-' ) after_al[str[i] - 'a']--, str[i + 1] = 'A', str[i + 2] = 'A', opt[str[i] - 'a'] = 1;
}
int flag = 1;
for ( int i = 0; i < len; ++i ) {
if ( islower ( str[i] ) ) {
if ( flag == 1 ) value += before_al[str[i] - 'a'];
else if ( flag == -1 ) value -= before_al[str[i] - 'a'];
}
else if ( str[i] == '+' ) flag = 1;
else if ( str[i] == '-' ) flag = -1;
}
printf ( " value = %d\n", value );
for ( int i = 0; i < 26; ++i ) {
if ( opt[i] ) printf ( " %c = %d\n", i + 'a', after_al[i] );
}
}
return 0;
}