不少航空公司都会提供优惠的会员服务,当某顾客飞行里程累积达到一定数量后,可以使用里程积分直接兑换奖励机票或奖励升舱等服务。现给定某航空公司全体会员的飞行记录,要求实现根据身份证号码快速查询会员里程积分的功能。
输入格式:
输入首先给出两个正整数N(≤10的5次方 )和K(≤500)。其中K是最低里程,即为照顾乘坐短程航班的会员,航空公司还会将航程低于K公里的航班也按K公里累积。随后N行,每行给出一条飞行记录。飞行记录的输入格式为:18位身份证号码(空格)飞行里程。其中身份证号码由17位数字加最后一位校验码组成,校验码的取值范围为0~9和x共11个符号;飞行里程单位为公里,是(0, 15 000]区间内的整数。然后给出一个正整数M(≤10的5次方),随后给出M行查询人的身份证号码。
输出格式:
对每个查询人,给出其当前的里程累积值。如果该人不是会员,则输出No Info。每个查询结果占一行。
输入样例:
4 500
330106199010080419 499
110108198403100012 15000
120104195510156021 800
330106199010080419 1
4
120104195510156021
110108198403100012
330106199010080419
33010619901008041x
输出样例:
800
15000
1000
No Info
字符串hash+分离式链接法
自己首先的思想:先开一个数组,里面只保存指针。但是没法搞啊。因为,我们首先要先定义他的长度,在输入n,但是我们定义长度是根据n定义的,所以不行啊。
于是就有了动态开数组。
ptr *data;//相当于node **data;首先(*data)是一个指向node的指针,其次
*data可以理解为数组,不过是指向他第一个空间的地址
tep->data=(ptr*)malloc(sizeof(ptr)*size);//malloc前面的参数ptr*,说明data
是一个指向ptr型的指针,后面sizeof(ptr)也能说明。
错误:当时写成tep->data=(ptr*)malloc(sizeof(node)*size)
然后下面的初始化就变为了tep->data[i]->next=NULL;
报错了。
错误原因:不理解ptr *data
的含义,数组里面的元素是指针。而自己认为还是node,而不是指针。
其次,至于初始化,虽然我们有tep->data=(ptr*)malloc(sizeof(node)*size)
,但只是开了指针的大小,但是指针没有指向任何空间。所以tep->data[i]->next=NULL;
报错了
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct NODE node;
typedef node *ptr;
typedef struct HASH{
ptr *data;
int tablesize;
}*hash;
struct NODE{
char id[20];
int len;
ptr next;
};
int findprime(int n)//找到tablesize的大小,是一个素数
{
n=(n%2)?n+2:n+1;//是偶数,则加1;奇数+2
int flag=0;
while(1)
{
flag=0;
for(int i=2;i*i<=n;i++)
{
if(!n%i){
flag=1;
break;
}
}
if(!flag) return n;
n+=2;
}
}
hash creathash(int n)//建立hash表
{
int size=findprime(n);
hash tep=(hash)malloc(sizeof(struct HASH));
tep->tablesize=size;
tep->data=(ptr*)malloc(sizeof(ptr)*size);
for(int i=0;i<size;i++)
{
ptr p=(ptr)malloc(sizeof(node));
p->next=NULL;
tep->data[i]=p;
}
return tep;
}
int hashpy(char *id,hash ha)
{
int ans=0;
for(int i=13;i<=17;i++)
{
if(id[i]=='x') ans=(ans*10+10)%ha->tablesize;
else ans=(ans*10+id[i]-48)%ha->tablesize;
}
return ans;
}
ptr find(hash ha,char *id,int num)
{
ptr p,tep;
p=ha->data[num]->next;
if(p==NULL) return NULL;
while(p)
{
if(!strcmp(p->id,id))
{
return p;
}
p=p->next;
}
return p;
}
void insert(hash ha,char *id,int len,int num)
{
ptr p,tep;
p=ha->data[num]->next;
tep=find(ha,id,num);
if(!tep)
{
tep=(ptr)malloc(sizeof(node));
strcpy(tep->id,id);
tep->len=len;
tep->next=p;
ha->data[num]->next=tep;
}
else tep->len+=len;
}
int main(void)
{
int n,k;
scanf("%d%d",&n,&k);
hash hash1=creathash(n);
char id[20];
int len;
for(int i=1;i<=n;i++)
{
scanf("%s%d",id,&len);
if(len<k) len=k;
int num=hashpy(id,hash1);
insert(hash1,id,len,num);
}
int que;
scanf("%d",&que);
while(que--)
{
scanf("%s",id);
ptr tep=find(hash1,id,hashpy(id,hash1));
if(tep)printf("%d\n",tep->len);
else printf("No Info\n");
}
return 0;
}