进阶实验5-3.1 航空公司VIP客户查询 (25分)--散列表存储

 

 注意到累积里程类型用long long;

#include <stdio.h>
#include <math.h>
#include <malloc.h>
#include <string.h>
#define KeyLength 18
typedef enum {false,true
             } bool;
typedef struct LNode {
    char ID[KeyLength+1];
    long long sum;//long long
    struct LNode *Next;
}*List,LNode;
typedef struct {
    int TableSize;
    List *HashList;
}*HashTable;
bool IsPrime(int n) {
    if(n==0||n==1)
        return false;
    if(n>2) {
        int i;
        for(i=2; i<=sqrt(n)+1; i++) {
            if(n%i==0)return false;
        }
    }
    return true;
}
int NextPrime(int n) {
    int i=n+1;
    while(!IsPrime(i))
        i++;
    return i;
}
HashTable Create(int size) {
    HashTable H=(HashTable)malloc(sizeof(HashTable));
    H->TableSize=NextPrime(size);
    H->HashList=(List*)malloc(sizeof(List)*H->TableSize);
    int i;
    for(i=0; i<H->TableSize; i++) {
        H->HashList[i]=(List)malloc(sizeof(List));
        H->HashList[i]->Next=NULL;
    }
    return H;
}
void Destroy(HashTable H) {
    LNode *p;
    int i;
    for(i=0; i<H->TableSize; i++) {
        p=H->HashList[i];
        free(p);
    }
    free(H);
}
int hash(HashTable H,char *s) {
    return atoi(s+KeyLength-4)%H->TableSize;
}
void Insert(HashTable H,LNode *node,int key) {
    LNode *p=H->HashList[key];
    int flag=0;
    while(p->Next) {
        if(strcmp(p->Next->ID,node->ID)==0) {
            flag=1;
            p->Next->sum+=node->sum;//累积里程
            break;
        }
        p=p->Next;
    }
    if(!flag) {
        p->Next=node;
        p=node;
        p->Next=NULL;
    }
}
void Traverse(HashTable H,char *s,int key) {
    LNode *p=H->HashList[key]->Next;
    while(p) {
        if(strcmp(p->ID,s)==0) {
            printf("%lld\n",p->sum);
            break;
        }
        p=p->Next;
    }
    if(!p)
        printf("No Info\n");
}
int main() {
    int n,k;
    scanf("%d %d",&n,&k);
    int i;
    char num[KeyLength+1]="";
    int sum,key;
    HashTable H=Create(n);
    for(i=0; i<n; i++) {
        scanf("%s %lld",num,&sum);
        key=hash(H,num);
        LNode *node=(LNode *)malloc(sizeof(LNode));
        strcpy(node->ID,num);
        if(sum<k)
            sum=k;
        node->sum=sum;
        node->Next=NULL;
        Insert(H,node,key);

    }
    int m;
    scanf("%d",&m);
    char str[KeyLength+1];
    for(i=0; i<m; i++) {
        scanf("%s",str);
        key=hash(H,str);
        Traverse(H,str,key);
    }
    Destroy(H);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/snzhong/p/12433275.html