全部博文(68)
分类: C/C++
2012-01-25 22:15:58
Using (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?
答案:871198282
#include
#include
int getVal(const char* s)
{
int sum=0;
for(; *s; ++s)
sum += (int) (*s-'A'+1);
return sum;
}
struct Node
{
char *str;
struct Node *next;
struct Node *pre;
};
int main(void)
{
struct Node *begin, *cur, *tmp, *scur;
int c=0, n=0;
int idx = 0;
begin = cur = NULL;
FILE *pFile;
pFile = fopen("names.txt", "r");
if (pFile != NULL)
{
while((c = getc(pFile)) != EOF)
{
if (c == '"')
{
n = (n+1) % 2;
if (n)
{
tmp = (struct Node*)calloc (1, sizeof(struct Node));
if(cur == NULL){
begin = tmp;
begin->pre = NULL;
}
else{
cur->next = tmp;
tmp->pre = cur;
}
cur = tmp;
cur->str = (char *)calloc (30, sizeof(char));
cur->next = NULL;
}
else
{
idx = 0 ;
continue;
}
}
if (c == ',')
continue;
if (c>='A' && c<='Z')
cur->str[idx++] = c;
}
fclose(pFile);
//Start sorting : Insert
cur = begin->next;
while (cur != NULL)
{
scur = begin;
while(scur != cur)
{
if (strcmp(scur->str, cur->str) <= 0){
scur = scur->next;
}
else{
tmp = cur;
if (cur->next != NULL)
{
cur->pre->next = cur->next;
cur->next->pre = cur->pre;
}
else{
cur->pre->next = NULL;
}
cur = cur->pre;
if (scur->pre == NULL){
tmp->pre = NULL;
tmp->next = begin;
begin->pre = tmp;
begin= tmp;
}
else{
scur->pre->next = tmp;
tmp->next = scur;
tmp->pre = scur->pre;
scur->pre = tmp;
}
break;
}
}
cur = cur->next;
}
long long sum = 0LL;
cur = begin;
n = 1;
while(cur != NULL)
{
sum += getVal(cur->str)*n;
n++;
cur = cur->next;
}
printf("%lli\n", sum);
}
else
{
perror("Can't Open the names.txt!");
return 1;
}
return 0;
}