UVA - 327 Evaluating Simple C Expressions

来源:互联网 发布:javascript实例小游戏 编辑:程序博客网 时间:2024/06/05 16:10

题目大意:根据 ++、– 的性质计算,a = 1,b = 2……z = 26。输出计算结果和计算后各字母的值。

解题思路:暴力模拟。每碰到一个字母,检查该字母前后是否存在前缀,若存在,将改字母对应的值 +1 或 -1,找到字母前的一个符号 + 或 -,进行对应计算,接着检查该字母是否存在后缀,若存在,将改字母对应的值 +1 或 -1。输出即可。注意自增符号前缀和后缀的计算顺序是不同的,有点难处理。

#include<iostream>#include<cstdio>#include<cstdlib>#include<cstring>#include<cmath>using namespace std;char tmp[1000];char str[1000];char ch[30][2];int sum, tag;int cmp(const void*a, const void*b) {    return strcmp((char*)a, (char*)b);}int before(int i) {    if (i > 1 && str[i-1] == str[i-2]) {        if (str[i-1] == '-') ch[tag][1] -= 1;           if (str[i-1] == '+') ch[tag][1] += 1;        str[i-1] = str[i-2] = ' ';        return 1;    }return 0;}int after(int i) {    int t = 0;    if (str[i+1] == str[i+2]) {        if (str[i+1] == '+') t = 1;        if (str[i+1] == '-') t = -1;            str[i+1] = str[i+2] = ' ';    }return t;}int main() {    while (gets(tmp)) {        printf("Expression: %s\n", tmp);        sum = 0;        int len = 0;        for (int i = 0; i < strlen(tmp); i++) {            if (tmp[i] == ' ') continue;            str[len++] = tmp[i];            }        tag = 0;        for (int i = 0; i < len; i++) {            if (str[i] >= 'a' && str[i] <= 'z') {                ch[tag][0] = str[i];                ch[tag][1] = str[i];                before(i);                int j = i;                while (j > 0 && str[j] != '+' && str[j] != '-') j--;                if (str[j] == '-') sum -= ch[tag][1] - 'a' + 1;                else sum += ch[tag][1] - 'a' + 1;                ch[tag][1] += after(i);                tag++;            }        }        printf("    value = %d\n", sum);        qsort(ch, tag, sizeof(ch[0]), cmp);        for (int i = 0; i < tag; i++)            printf("    %c = %d\n", ch[i][0], ch[i][1] - 'a' + 1);    }return 0;}
0 0
原创粉丝点击