题意很长,很麻烦的判断,给typedef a b 和 typeof a 两种操作,void 和errtype 两种类型,开始我考虑到每种情况的判断,细节很多,没有解出来,后来看人家的代码,问题其实没那么复杂,看输出就知道,只有errtype 和 void+若干个* 两种,所以在求得时候至于要用mp<string, int>维护*的个数就好了。注意的是这里初始化mp["viod"]=1,输出时mp-1个‘*’结束。
代码:
#include<iostream>
#include<map>
#include<string>
using namespace std;
map<string, int>mp;// represent the num of '*'
int solve(string a)
{
string temp="";
int num=0;
int len=a.size();
for(int i=0; i<len; i++)
{
if(a[i]=='&')
num--;
else if(a[i]=='*')
num++;
else
temp+=a[i];
}
int cnt=mp[temp];
int ans=0;
if(cnt>0)
{
ans=cnt+num;
}
else//原来 是 errtype
{
ans=0;
}
return ans;
}
int main()
{
int N;
int num;
string ch, a, b;
mp.clear();
mp["void"]=1;//初始化 !! 很重要!!
cin>>N;
while(N--)
{
cin>>ch;
if(ch=="typedef")
{
cin>>a>>b;
num=solve(a);
if(num<=0)
mp[b]=0;
else
mp[b]=num;
}
else if(ch=="typeof")
{
cin>>a;
num=solve(a);
num--;
if(num<0)
cout<<"errtype"<<endl;
else
{
cout<<"void";
for(int i=1; i<=num; i++)
cout<<"*";
cout<<endl;
}
}
}
return 0;
}
本文介绍了解决B-VasyaandTypes问题的方法。通过使用C++编程语言及map容器来跟踪不同类型中星号的数量,实现了对输入类型的转换与查询。文章详细解释了代码逻辑,并提供了完整的代码实现。
516

被折叠的 条评论
为什么被折叠?



