(Problem 22)Names scores

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 (Problem 22)Names scores 53 = 49714.

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

题目大意:

文件names.txt (右键另存为)是一个46K大小的文本文件,包含5000多个英文名字。利用这个文件,首先将文件中的名字按照字母排序,然后计算每个名字的字母值,最后将字母值与这个名字在名字列表中的位置相乘,得到这个名字的得分。

例如将名字列表按照字母排序后, COLIN这个名字是列表中的第938个,它的字母值是3 + 15 + 12 + 9 + 14 = 53。所以COLIN这个名字的得分就是938 (Problem 22)Names scores 53 = 49714.

文件中所有名字的得分总和是多少?

//(Problem 22)Names scores
// Completed on Mon, 18 Nov 2013, 15:03
// Language: C
//
// 版权所有(C)acutus (mail: acutus@126.com)
// 博客地址:http://www.cnblogs.com/acutus/#include <stdio.h>
#include <ctype.h>
#include <stdlib.h> struct str{
char name[];
}; char a[]; int namevalue(char *s)
{
int i, sum;
i = sum = ;
while(s[i]) {
sum += (s[i] - 'A' + );
i++;
}
return sum;
} int cmp(const void *a, const void *b)
{
return strcmp((*(struct str*)a).name, (*(struct str*)b).name);
} void solve(void)
{
FILE *fp;
int i, j, k;
char *s, c;
long long sum = ; struct str namestring[]; fp = fopen("names.txt", "r");
fseek(fp, , SEEK_END);
int file_size;
file_size = ftell(fp);
fseek(fp, , SEEK_SET);
s = (char*)malloc(file_size * sizeof(char));
fread(s, sizeof(char), file_size, fp); i = j = k = ;
while(i <= file_size) {
c = s[i++];
if(!isalpha(c)) {
if(c == ',') {
j = ;
strcpy(namestring[k++].name, a);
memset(a,'\0', * sizeof(char));
}
} else {
a[j++] = c;
}
}
strcpy(namestring[k].name, a);
memset(a,'\0', * sizeof(char)); qsort(namestring, , sizeof(namestring[]),cmp); for(i = ; i <= ; i++) {
sum += (namevalue(namestring[i].name) * (i + ));
}
printf("%lld\n",sum);
} int main(void)
{
solve();
return ;
}
Answer:
871198282
上一篇:AbstractFactoryPattern(抽象工厂)


下一篇:谈谈JavaScript事件