[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

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

好了,分析了这些,我们来写程序
#include<algorithm>



usingnamespacestd;

usingnamespaceboost;



intworth(stringtmp){

intworthOfString=0;

for(inti=0; i<tmp.length(); i++){

worthOfString
+=int(tmp[i]-64);

}

returnworthOfString;

}



intmain()

{

intsum=0;

vector
<string>names;

vector
<string>::iterator iter;

fstream file(
"names.txt",ios::in);

strings;

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(inti=0;i<names.size();i++){

sum
+=(i+1)
worth(names[i]);

}

cout
<<sum<<endl;

return0;

}

[Project Euler] Problem 22

由于很多算法在标准库里都有提供,所以,这道题也就迎刃而解了
原文链接: https://www.cnblogs.com/xianglan/archive/2011/03/06/1972587.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/21897

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月7日 下午11:52
下一篇 2023年2月7日 下午11:53

相关推荐