UVa486 - English-Number Translator

#include <iostream>
#include <fstream>
#include <cstdio>
#include <sstream>
#include <algorithm>
#include <string>
#include <map>
#include <sstream>
#include <iomanip>
#include <vector>
#include <iterator>

using namespace std;

void init();

map<string, int> m;

int find_num(vector<string> v, int b, int e);

int main()
{
	vector<string> v;
	vector<string>::iterator pos, million_pos, thousand_pos;
	string str, tmp;


#ifndef ONLINE_JUDGE
	ifstream cin("d:\\OJ\\uva_in.txt");
#endif

	init();

	while (getline(cin, str)) {
		istringstream line(str);
		v.clear();
		while (line >> tmp) {
			v.push_back(tmp);
		}

		//copy(v.begin(), v.end(), ostream_iterator<string>(cout, " "));
		//cout << endl;

		million_pos = find(v.begin(), v.end(), "million");
		thousand_pos = find(v.begin(), v.end(), "thousand");

		pos = find(v.begin(), v.end(), "negative");
		if (pos != v.end()) {
			cout << "-";
		}

		if (million_pos == v.end()) {
			if (thousand_pos == v.end()) {


				cout << find_num(v, 0, v.size()) << endl;

			} else {
				cout << find_num(v, 0, distance(v.begin(), thousand_pos));
				cout << setfill('0') << setw(3) << find_num(v, distance(v.begin(), thousand_pos) + 1, v.size());
				cout << endl;
			}
		} else {
			if (thousand_pos == v.end()) {
				cout << find_num(v, 0, distance(v.begin(), million_pos));
				cout << "000";
				cout << setfill('0') << setw(3) << find_num(v, distance(v.begin(), million_pos) + 1, v.size());
				cout << endl;
			} else {
				cout << find_num(v, 0, distance(v.begin(), million_pos));
				cout << setfill('0') << setw(3) << find_num(v, distance(v.begin(), million_pos) + 1, distance(v.begin(), thousand_pos));
				cout << setfill('0') << setw(3) << find_num(v, distance(v.begin(), thousand_pos) + 1, v.size()) << endl;
			}
		}

	}
	return 0;
}

void init()
{
	m["zero"] = 0;
	m["one"] = 1;
	m["two"] = 2;
	m["three"] = 3;
	m["four"] = 4;
	m["five"] = 5;
	m["six"] = 6;
	m["seven"] = 7;
	m["eight"] = 8;
	m["nine"] = 9;
	m["ten"] = 10;
	m["eleven"] = 11;
	m["twelve"] = 12;
	m["thirteen"] = 13;
	m["fourteen"] = 14;
	m["fifteen"] = 15;
	m["sixteen"] = 16;
	m["seventeen"] = 17;
	m["eighteen"] = 18;
	m["nineteen"] = 19;
	m["twenty"] = 20;
	m["thirty"] = 30;
	m["forty"] = 40;
	m["fifty"] = 50;
	m["sixty"] = 60;
	m["seventy"] = 70;
	m["eighty"] = 80;
	m["ninety"] = 90;

}

int find_num(vector<string> v, int b, int e)
{
	vector<string>::iterator begin, end, pos;
	int ans = 0;

	begin = end = v.begin();
	advance(begin, b);
	advance(end, e);

	pos = find(begin, end, "hundred");

	if (pos == end) {

		for (vector<string>::iterator i = begin; i != end; i++) {
			ans += m[*i];
		}
	} else {

		for (vector<string>::iterator i = begin; i != pos; i++) {
			ans += m[*i] * 100;
		}

		for (vector<string>::iterator i = pos + 1; i != end; i++) {
			ans += m[*i];
		}

	}

	return ans;
}

你可能感兴趣的:(UVa486 - English-Number Translator)