ZeroJudge a017. 五則運算


評分:2.5 分,滿分為 5。

題目連結

題意

給一個中序的五則運算式,要你把答案算出來(有刮號代表最優先)

解題方法

我們先把他從中序轉到後序,在就可以比較好的用 stack 計算出答案。而兩部分剛好都有 ZeroJudge 題目可以先寫。 這兩部分我也都有教學,非常建議去看看!
f698. 後序運算式 f377. 運算式轉換
只是這兩題寫完的可能不能直接用,要記得處理 %

#include <bits/stdc++.h>
using namespace std;
int main() {
	string s, c;
	while(getline(cin, s)) {
		stack <string> st;
		vector <string> ans;
		stringstream ss; ss << s; 
		while(ss >> c) {
			if(c == ")") {
				while(st.top() != "(") {
					ans.push_back(st.top());
					st.pop();
				}
				st.pop();
			} else if(c == "(") {
				st.push("(");
			} else if(c == "*" || c == "/" || c == "%") {
				while(!st.empty() && (st.top() == "*" || st.top() == "/" || st.top() == "%")) {
					ans.push_back(st.top());
					st.pop();
				} 
				st.push(c);
			} else if(c == "+" || c == "-") {
				while(!st.empty() && (st.top() == "*" || st.top() == "/" || st.top() == "+" || st.top() == "-" || st.top() == "%")) {
					ans.push_back(st.top());
					st.pop();
				} 
				st.push(c);
			} else {
				ans.push_back(c);
			}
		}
		
		while(!st.empty()) {
			ans.push_back(st.top());
			st.pop();
		}

		
		stack <int> st2;
		for(string x : ans) {
			if(x == "+" || x == "-" || x == "/" || x == "*" || x == "%") {
				signed int sc = st2.top(); st2.pop(); // 題目說是有號整數
				signed int ft = st2.top(); st2.pop(); 
				if(x == "+") st2.push(ft+sc);
				if(x == "-") st2.push(ft-sc);
				if(x == "*") st2.push(ft*sc);
				if(x == "/") st2.push(ft/sc);
				if(x == "%") st2.push(ft%sc);
			} else {
				st2.push(stoi(x));
			}
		}
		cout << st2.top() << '\n';
	}
}

發表迴響

Blog at WordPress.com.

探索更多來自 Coding Prep 演算法資料結構教學 的內容

立即訂閱即可持續閱讀,還能取得所有封存文章。

Continue reading