[Project Euler] Problem 22

Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.

For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 53 = 49714.

What is the total of all the name scores in the file?

names.txt 是一份包含5163个姓名的文件。这5163个名字由引号和逗号分开

它们是像这样排列的。"MARY","PATRICIA","LINDA","BARBARA","ELIZABETH"。。。。。。

按照题目的要求,我们先把这5163个名字按字母顺序排列

对于每个名字,我们计算它的“权重”与它的排名的积

然后把所有的积的和求出来

boost中提供了简单的分割string的方法

我们把string分割后存在一个vector<string>里

而在标准c++算法库里也提供了vector的排序

好了,分析了这些,我们来写程序

#include < algorithm >

using namespace std;
using namespace boost;

int worth( string tmp){
int worthOfString = 0 ;
for ( int i = 0 ; i < tmp.length(); i ++ ){
worthOfString
+= int (tmp[i] - 64 );
}
return worthOfString;
}

int main()
{
int sum = 0 ;
vector
< string > names;
vector
< string > ::iterator iter;
fstream file(
" names.txt " ,ios:: in );
string s;
getline(file,s);
file.close();
tokenizer
<> tok(s);
for (tokenizer <> ::iterator beg = tok.begin(); beg != tok.end(); ++ beg)
{
names.push_back(
* beg);
}
sort(names.begin(),names.end());
for ( int i = 0 ;i < names.size();i ++ ){
sum
+= (i + 1 ) * worth(names[i]);
}
cout
<< sum << endl;
return 0 ;
}

由于很多算法在标准库里都有提供,所以,这道题也就迎刃而解了

你可能感兴趣的:(project)