跳到正文

题解

UVA486 题解

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

文章信息

发布
2025年1月3日
收录
2025年12月12日
更新
2026年9月27日
篇幅
约 4 分钟
获赞
10
题目
UVA486

版本

  1. v1当前

题目传送门

思路

一道小模拟,但是有一些细节。

对于每一组测试,用 getline 读入一行字符串,然后拆成单词。我们设临时变量为 TT,答案总和为 SS。

  • 判断单词是否为 zero,是的话输出 00。
  • 如果第一个单词是 negative,则将最终答案符号 FF 设为 −1-1。
  • 如果当前单词 ≤90\le90,设当前数字为 NN,则更新 TT,T←T+NT\gets T+N。
  • 如果当前单词是 hundred,则更新 TT,T←T×100T\gets T\times100。
  • 如果当前数字为 thousand 或 million,更新的 SS 分别为 S←S+1000TS\gets S+1000T 和 S←S+1000000TS\gets S+1000000T,并将 TT 清零。

最后一次更新的 TT 并不会加在 SS 中,所以要输出 F×(N+T)F\times(N+T)。

注意事项

  • hundred 的更新与 thousand 和 million 不同,因为每 10310^3 为一级,hundred 用来表示一级中的数字。

AC CODE

C++
#include<bits/stdc++.h>
using namespace std;
int calc(string s){
	if(s=="negative")
		return -1;
	else if(s=="one")
		return 1;
	else if(s=="two")
		return 2;
	else if(s=="three")
		return 3;
	else if(s=="four")
		return 4;
	else if(s=="five")
		return 5;
	else if(s=="six")
		return 6;
	else if(s=="seven")
		return 7;
	else if(s=="eight")
		return 8;
	else if(s=="nine")
		return 9;
	else if(s=="ten")
		return 10;
	else if(s=="eleven")
		return 11;
	else if(s=="twelve")
		return 12;
	else if(s=="thirteen")
		return 13;
	else if(s=="fourteen")
		return 14;
	else if(s=="fifteen")
		return 15;
	else if(s=="sixteen")
		return 16;
	else if(s=="seventeen")
		return 17;
	else if(s=="eighteen")
		return 18;
	else if(s=="nineteen")
		return 19;
	else if(s=="twenty")
		return 20;
	else if(s=="thirty")
		return 30;
	else if(s=="forty")
		return 40;
	else if(s=="fifty")
		return 50;
	else if(s=="sixty")
		return 60;
	else if(s=="seventy")
		return 70;
	else if(s=="eighty")
		return 80;
	else if(s=="ninety")
		return 90;
	else if(s=="hundred")
		return 100;
	else if(s=="thousand")
		return 1000;
	else if(s=="million")
		return 1000000;
	return 0;
}
int main(){
	string s;
	while(getline(cin,s)){
		int l=0,ans=0,f=1;
		for(int i=0;i<s.size();++i)
			if(s[i]==' ')
				++i;
			else{
				string t="";
				while(s[i]!=' '&&i<s.size())
					t+=s[i++];
				int num=calc(t);
				if(num==-1)
					f=-1;
				else if(num==100)
					l*=100;
				else if(num==1000||num==1000000)
					ans+=l*num,l=0;
				else l+=num;
			}
		cout<<f*(ans+l)<<"\n";
	}
	return 0;
}
原文