牛客oj 習題5.1堆棧的使用&&習題5.2計算表達式(逆波蘭)

 

送分題。

 

 

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
#include <vector>
#include <stack>
#include <climits>
 
using namespace std;
 
const int MAXN = 1005;
const int INF = INT_MAX;
 
int main(){
  //  freopen("in.txt", "r", stdin);
    int n, num;
    string str;
    while(~scanf("%d", &n)){
    	stack<int> sta;
    	for(int i = 0; i < n; i++){
	    	cin >> str;
	    	if(str == "P"){
	    		scanf("%d", &num);
	    		sta.push(num);
	    	}
	    	else if(str == "O"){
	    		if(sta.empty()) continue;
	    		sta.pop();
	    	}
	    	else if(str == "A"){
	    		if(sta.empty()) printf("E\n");
	    		else printf("%d\n", sta.top());
	    	}
    	}
    	printf("\n");
    }
    return 0;
}

 

 

計算表達式這類題,看似思路清晰,可是不知爲何總是敲不好,頭疼。只好多練了。

 

 

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
#include <vector>
#include <stack>
#include <cctype>
#include <climits>
 
using namespace std;
 
const int MAXN = 1005;
const int INF = INT_MAX;

int cur;

int Priority(char x){
	if(x == '#') return 0;
	else if(x == '$') return 1;
	else if(x == '+' || x == '-') return 2;
	else if(x == '*' || x == '/') return 3;
}

double Getnum(string str){
	double numtmp = 0;
	while(isdigit(str[cur])){
		numtmp = numtmp*10 + (str[cur] - '0');
	//	printf("%d,,,", numtmp);
	//	cout << str[cur] << ",,,";
		cur++;
	}
//	printf("%d,,,", numtmp);
	return numtmp;
}

double Caculate(char op, double x, double y){
	if(op == '+') return x+y;
	else if(op == '-') return y-x;
	else if(op == '*') return x*y;
	else if(op == '/') return y/x;//注意是後面的數除前面的數 
}
 
int main(){
  //  freopen("in.txt", "r", stdin);
    string str;
    while(cin >> str){
    	stack<double> number;
		stack<char> oper;
    	str += '$';
    	oper.push('#');
    	cur = 0;
//    	cout << oper.top();
    	while(cur < str.size()){
    		if(isdigit(str[cur])){
    		//	printf("%d......", cur);
    			number.push(Getnum(str));
    		//	printf("%d %d\n", number.top(), cur);
    		}
    		else if(Priority(str[cur]) > Priority(oper.top())){
    			oper.push(str[cur]);
    			cur++;
    		}
    		else if(Priority(str[cur]) <= Priority(oper.top())){//如果當前符號壓不住棧頂的符號,cur不增加 
    			double x = number.top();
    			number.pop();
    			double y = number.top();
    			number.pop();
    			number.push(Caculate(oper.top(), x, y));
    			//cout << oper.top() << "........";
    			oper.pop();
    			//cout << oper.top() << endl;
    		//	cout << number.top() << "......" << endl;
    		}
    	}
    	printf("%.lf\n", number.top());
    }
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章