11-散列1 電話聊天狂人 (25分)

給定大量手機用戶通話記錄,找出其中通話次數最多的聊天狂人。
輸入格式:
輸入首先給出正整數N(≤10^5),爲通話記錄條數。隨後N行,每行給出一條通話記錄。簡單起見,這裏只列出撥出方和接收方的11位數字構成的手機號碼,其中以空格分隔。
輸出格式:
在一行中給出聊天狂人的手機號碼及其通話次數,其間以空格分隔。如果這樣的人不唯一,則輸出狂人中最小的號碼及其通話次數,並且附加給出並列狂人的人數。

輸入樣例:
4
13005711862 13588625832
13505711862 13088625832
13588625832 18087925832
15005713862 13588625832
輸出樣例:

13588625832 3


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 12

typedef struct ListNode *Position;
typedef struct HTable *HashTable;
struct ListNode {
	char data[N];
	int count;
	Position next;
};
struct HTable {
	Position list;
	int size;
};
HashTable CreatTable(int n);
void Insert(HashTable H, char *key);
void Solve(HashTable H);
int NextPrime(int n);

int main() {
	int i, n;
	char key[N];
	HashTable H;
	scanf("%d", &n);
	H = CreatTable(n * 2);
	for (i = 0; i < 2 * n; i++) {
		scanf("%s", key);
		Insert(H, key);
	}
	Solve(H);
	return 0;
}

HashTable CreatTable(int n) {
	HashTable H;
	int i;
	H = (HashTable)malloc(sizeof(struct HTable));
	H->size = NextPrime(n);
	H->list = (Position)malloc(H->size*sizeof(struct ListNode));
	for (i = 0; i < H->size; i++) 
		H->list[i].next = NULL;	
	return H;
}

void Insert(HashTable H, char *key) {
	Position p, temp;
	int h;
	h = (atoi(key + 6)) % H->size;
	p = H->list[h].next;
	while (p && strcmp(p->data, key)) {
		p = p->next;
	}
	if (p) p->count++;
	else {
		temp = (Position)malloc(sizeof(struct ListNode));
		strcpy(temp->data, key);
		temp->count = 1;
		temp->next = H->list[h].next;
		H->list[h].next = temp;
	}
}


void Solve(HashTable H) {
	int i, max = 0, num;
	char min[N];
	Position p;
	for (i = 0; i < H->size; i++) {
		p = H->list[i].next;
		while (p) {
			if (p->count > max) {
				max = p->count;
				strcpy(min, p->data);
				num = 1;
			}
			else if (p->count == max) {
				num++;
				if (strcmp(p->data, min) < 0)
					strcpy(min, p->data);
			}
			p = p->next;
		}
	}

	if(num == 1)
		printf("%s %d\n", min, max);
	else
		printf("%s %d %d\n", min, max, num);
	
}

int NextPrime(int n) {
	int i, j;
	n = (n % 2) ? n + 2 : n + 1;
	for (i = n;; i += 2) {
		for (j = 3; j*j <= i && i%j; j++);
		if (j*j > i) break;
	}
	return i;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章