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?
--------------------
- #include <stdio.h>
-
#include <string.h>
-
#include <stdlib.h>
-
#include <sys/stat.h>
-
#include <sys/types.h>
-
#include <fcntl.h>
-
-
typedef struct _node {
-
char *name;
-
int nr;
-
struct _node *next;
-
} node;
-
-
-
node *insert(node **head, node *new)
-
{
-
node *node=*head, *pnode = NULL;
-
-
while (node) {
-
if (strcmp(node->name, new->name) > 0)
-
break;
-
else {
-
pnode = node;
-
node = node->next;
-
}
-
}
-
-
if (pnode) {
-
pnode->next = new;
-
new->next = node;
-
} else { /* head */
-
*head = new;
-
new->next = node;
-
}
-
-
return new;
-
}
-
-
/* hash */
-
int node_map(node **domain, char *name)
-
{
-
int key;
-
node *new = malloc(sizeof(node));
-
-
memset(new, 0, sizeof(node));
-
new->name = strdup(name);
-
key = (name[0] - 'A') % 26;
-
insert(&domain[key], new);
-
-
return 0;
-
}
-
-
void node_unmap(node **domain, node *node)
-
{
-
}
-
-
unsigned int score(char *name, int nr)
-
{
-
int i, sum = 0;
-
for (i = 0; i < strlen(name); i++) {
-
sum += name[i] - '@';
-
}
-
-
return sum * nr;
-
}
-
-
node *domain[26];
-
int main(int argc, const char *argv[])
-
{
-
node *node;
-
int i, sum = 0, count = 0;
-
FILE *fp;
-
char buf[1024];
-
char *lineptr[1] ={buf};
-
int n;
-
-
fp = fopen(argv[1], "r");
-
if (!fp) {
-
perror("open error");
-
exit(-1);
-
}
-
-
-
while (getdelim(lineptr, &n, ',', fp) > 0) {
-
char *quote = strchr(buf+1, '"');
-
if (quote) *quote = '\0';
-
node_map(domain, buf+1);
-
}
-
-
-
for (i = 0; i < sizeof(domain)/sizeof(domain[0]); i++) {
-
node = domain[i];
-
while (node) {
-
count++;
-
sum += score(node->name, count);
-
node = node->next;
-
}
-
}
-
-
printf("sum: %d\n", sum);
-
-
return 0;
-
}
-
-
用hash表排序.不知道有没有优化的办法.
阅读(1564) | 评论(0) | 转发(0) |