CF87B解题报告
CF87B 解题报告
题意
&K* 是一种编程语言,语言只有两种基本数据类型 void 和 errtype。此外,该语言具有运算符 typedef 和 typeof。
typedef 和 typeof 具体含义见题面,类似于 c++ 中的定义变量和查看变量对应变量类型,就是一个映射关系。
对于每一次 typeof,输出对应的类型,如果匹配不到,那么输出 errtype
。
分析
很明显是一道模拟题,对于每一个 typedef 的定义,通过 map 记录对应类型 *
的个数和 &
的个数差。对于 typeof,将这个变量按 typedef 的方法看 map 中是否存储着对应的变量名,输出时还原 *
。
对于不合法的情况,考虑样例,发现在变量类型前不能有 &
只能在后面有 *
,所以在记录这两个字符个数差的时候,如果是负数,那么就是不合法的。这个发现也减少了代码量,在还原的时候只需要还原 *
就好了。
代码
#include<bits/stdc++.h>
using namespace std;
int n;
string act;
map<string,int> mp;
int type(string s){
int cnt1 = 0, cnt2 = 0;
while (s[0] == '&'){//题目确保了'&'一定在字符串前面,'*'在后面
cnt1++;
s.erase(0, 1);
}
while (s[s.size() - 1] == '*'){
cnt2++;
s.erase(s.size() - 1, 1);
}
if (mp.count(s) == 0) return -1;//之前没有定义过这种类型
int t = mp[s];
if (t == -1) return -1;//如果是errtype
t += cnt2 - cnt1;//记录'*'和'&'的数量差
if (t < 0) t = -1;//'*'比'&'少 不合法
return t;
}
void run_typedef(){
string s1, s2;
cin >> s1 >> s2;
mp[s2] = type(s1);
}
void run_typeof(){
string s;
cin >> s;
int t = type(s);//还原出要加多少个'*'或者不合法
if (t == -1) cout << "errtype\n";
else{
cout << "void";
for(int i = 1; i <= t; i++) cout << "*";
cout << endl;
}
}
int main(){
mp["void"] = 0, mp["errtype"] = -1;
cin >> n;
for (int i = 1; i <= n; i++){
cin >> act;
if (act == "typedef") run_typedef();
if (act == "typeof") run_typeof();
}
return 0;
}