跳到正文

题解

题解:P14305 【MX-J27-T2】转换

miyachn约 4 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年5月19日
篇幅
约 4 分钟
题目
P14305

版本

  1. v1当前

题目传送门

核心思想:使用栈来处理运算符优先级,模拟表达式的求值过程。 将表达式拆分为操作数和运算符并使用两个栈分别存储操作数类型和运算符,按照运算符优先级进行计算,最终栈顶即为表达式的结果类型。

接下来列出所有求表达式运算结果时需要注意的定义:

  1. 类型优先级定义:

    将六种数据类型按照精度和转换规则映射为数值等级。char和bool等级为0,int为1,longlong为2,float为3,double为4。

  2. 运算符优先级:

    • ,的优先级为1
    • +和*的优先级为2
  3. 类型转换规则:

    • char和bool在运算前自动转换为int
    • 同类型运算结果保持原类型
    • 整型之间运算取精度更高的类型
    • 浮点型之间运算取精度更高的类型
    • 整型与浮点型混合运算取精度更高的浮点类型
    • 逗号运算符返回第二个操作数的类型

AC Code:
C++
#include<bits/stdc++.h>
using namespace std;
map<string,int>r={
	{"char",0},
	{"bool",0},
	{"int",1},
	{"longlong",2},
	{"float",3},
	{"double",4}
};
int p(char o){
	if(o==',') return 1;
	if(o=='+'||o=='*') return 2;
	return 0;
}
string t(string a,string b){
	string x=(a=="char"||a=="bool")?"int":a;
	string y=(b=="char"||b=="bool")?"int":b;
	if((x=="int"||x=="longlong")&&(y=="int"||y=="longlong"))
		return r[x]>r[y]?x:y;
	if((x=="float"||x=="double")&&(y=="float"||y=="double"))
		return r[x]>r[y]?x:y;
	if((x=="int"||x=="longlong")&&(y=="float"||y=="double"))
		return y;
	if((y=="int"||y=="longlong")&&(x=="float"||x=="double"))
		return x;
	return "double";
}
string c(string a,char o,string b){
	if(o==',')return b;
	return t(a,b);
}

int main(){
	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);
	int x,T;
	cin>>x>>T;
	while(T--){
		string s,u;
		cin>>s;
    vector<string>v;
		for(char ch:s){
			if(ch=='+'||ch=='*'||ch==','){
				if(!u.empty()){
					v.push_back(u);
					u.clear();
				}
				v.push_back(string(1,ch));
			}else{
				u.push_back(ch);
			}
		}
		if(!u.empty()){
			v.push_back(u);
		}
		stack<string> st;
		stack<char> sc;
		for(const string&k:v){
			if(k=="+"||k=="*"||k==","){
				char o=k[0];
				while(!sc.empty()&&p(sc.top())>=p(o)){
					char op=sc.top();sc.pop();
					string b=st.top();st.pop();
					string a=st.top();st.pop();
					string r=c(a,op,b);
					st.push(r);
				}
				sc.push(o);
			}else{
				st.push(k);
			}
		}
		while(!sc.empty()){
			char op=sc.top(); sc.pop();
			string b=st.top(); st.pop();
			string a=st.top(); st.pop();
			string r=c(a,op,b);
			st.push(r);
		}
		cout<<st.top()<<'\n';
	}
	return 0;
}
原文