2022年6月10日 星期五

f640: 函數運算式求值

解題心得

用stack,把字串倒著看。

程式碼

#include<iostream>
#include<stack>
#include<vector>
#include <string>
using namespace std;

int main()
{
	int x, y, z;
	stack<int> st;
	vector<string> v;
	string s;
	while (cin >> s)
		v.push_back(s);
	for (int i = v.size() - 1; i >= 0; i--)
	{
		if (v[i] == "f")
		{
			x = st.top(); st.pop();
			x = 2 * x - 3;
			st.push(x);
		}
		else if (v[i] == "g")
		{
			x = st.top(); st.pop();
			y = st.top(); st.pop();
			x = 2 * x + y - 7;
			st.push(x);
		}
		else if (v[i] == "h")
		{
			x = st.top(); st.pop();
			y = st.top(); st.pop();
			z = st.top(); st.pop();
			x = 3 * x - 2 * y + z;
			st.push(x);
		}
		else
		{
			st.push(stoi(v[i]));
		}
	}
	cout << st.top();
	return 0;
}

沒有留言:

張貼留言