本文主要是介绍uva 327,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题意:计算结果,注意有二目运算符,并输出每个字符的值
#include <iostream>
#include <cstdio>
#include <cstring>
#include <deque>
#include <vector>
#include <algorithm>
using namespace std;
const int MAXN = 130;vector<char>var;
deque<int>que;
char str[MAXN];
int val[26];void Filter() //去掉空格
{int pos = 0;for (int i = 0 ; i < strlen(str) ; i++)if (str[i] != ' ')str[pos++] = str[i];str[pos] = '\0';
}bool havePrefix(int i) //前++,--
{if ((str[i-1]=='+' && str[i-2] == '+') ||( str[i-1]=='-' && str[i-2]=='-'))return true;return false;
}bool haveSuffix(int i) //后++,--
{if ((str[i+1]=='+' && str[i+2] == '+') ||( str[i+1]=='-' && str[i+2]=='-'))return true;return false;
}void PreProssess() //去掉二目运算符,并储存字符值
{while (!que.empty())que.pop_back();var.clear();for (int i = 0 ; i < strlen(str) ; i++){if (str[i] >= 'a' && str[i] <= 'z'){var.push_back(str[i]);if (i >= 2 && havePrefix(i)){if (str[i-1] == '+')val[str[i] - 'a']++;else val[str[i] - 'a']--;int n = val[str[i]-'a'];que.push_back(n);str[i-1] = str[i-2] = ' ';}else if (i <= strlen(str)-3 && haveSuffix(i)){int n = val[str[i] - 'a'];que.push_back(n);if (str[i+1] == '+')val[str[i] - 'a']++;else val[str[i] - 'a']--;str[i+1] = str[i+2] = ' '; }else {int n = val[str[i] - 'a'];que.push_back(n);}}}
}int getsum()
{for (int i = 0 ; i < strlen(str) ; i++){if (str[i] == '+' || str[i] == '-'){int a = que.front();que.pop_front();int b = que.front();que.pop_front();if(str[i] == '+')que.push_front(a+b);else que.push_front(a-b);}}return que.front();
}void solve()
{for (int i = 0 ; i < 26 ; i++)val[i] = i+1;Filter();PreProssess();int sum = getsum();printf(" value = %d\n",sum);sort(var.begin(),var.begin()+var.size());for (int i = 0 ; i < var.size() ; i++)printf(" %c = %d\n",var[i],val[var[i]-'a']);
}int main()
{while (gets(str)){printf("Expression: %s\n",str);solve();}return 0;
}
这篇关于uva 327的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!