uva_327-Evaluating Simple C Expressions

来源:互联网 发布:全球手机电视直播软件 编辑:程序博客网 时间:2024/05/05 18:17
/**这道题貌似是一道用树解决的题,但是我一直没想到怎么用比较 *好,反而是数组的方法一下就想到了。。。具体思路是: * 1.记录计算结果时字母的值 * 2.记录操作符 + 或 - * 3.如果是 ++ 或 -- 标记与之相连的字母,最后改变该字母值 */#include <cstdio>#include <cstring>#include <cctype>using namespace std;#define VAL0#define Y1#define MAXL 27#define MAXO 100#define MAX 1000char operate[MAXO];             //记录符号int count[MAXL];                //统计改变量(++、--)int letter[MAXL][2];            //记录字母的值和是否存在该字母int val[MAXL];                  //计算时的实际值大小int oper_num, sum, letter_num;  //符号、字母的个数和//初始化void init() {    oper_num  = 0;    sum = 0;    letter_num = 0;    change_num = 0;    memset(letter, 0, sizeof(letter));    memset(val, 0, sizeof(val));}//输入处理void manage_input(char *str1) {int t(0);char str[MAX];         //保存没有空格的字符串for(int i = 0; '\0' != str1[i]; i ++){if( !isspace(str1[i]) ) str[t++] = str1[i];}    for(int i = 0; i < t; i ++) {        if( isalpha(str[i]) ) {         //如果是字母,记录值            letter[str[i]-'a'][VAL] = str[i]-'a'+1;            if( count[str[i]-'a'] ) {                letter[str[i]-'a'][VAL] += count[str[i]-'a'];                count[str[i]-'a'] = 0;            }            val[letter_num++] = letter[str[i]-'a'][VAL];            letter[str[i]-'a'][Y] = 1;        } else {                        //如果是标点            if( '+' == str[i] ) {                if( '+' == str[i+1] ) { //如果是++,标记与之相连的字母                    if( isalpha(str[i-1]) ) count[str[i-1]-'a'] = 1;                    if( isalpha(str[i+2]) ) count[str[i+2]-'a'] = 1;                    i ++;                } else operate[oper_num++] = str[i];            } else {                if( '-' == str[i+1] ) { //同++                    if( isalpha(str[i-1]) ) count[str[i-1]-'a'] = -1;                    if( isalpha(str[i+2]) ) count[str[i+2]-'a'] = -1;                    i ++;                } else operate[oper_num++] = str[i];            }        }    }}//计算结果int calc() {    int i(0), j(0);    int sum = val[i++];    while( i < letter_num && j < oper_num ) {        if( '+' == operate[j++] ) sum += val[i];        else sum -= val[i];        i ++;    }    return sum;}//改变需要改变的字母值void change() {    for(int i = 0; i < MAXL; i ++) {            if( count[i] ) {                letter[i][VAL] += count[i];                count[i] = 0;            }    }}int main(int argc, char const *argv[]) {#ifndef ONLINE_JUDGE    freopen("test.in", "r", stdin);#endif    char str[MAX];    while( gets(str) ) {        init();        manage_input(str);        change();        printf("Expression: %s\n", str);        printf("    value = %d\n", calc());        for(int i = 0; i < MAXL; i ++) {            if( letter[i][Y] )                printf("    %c = %d\n", i+'a', letter[i][VAL]);        }    }    return 0;}


原创粉丝点击