PTA-数据结构5-45 航空公司VIP客户查询 (25分)

    xiaoxiao2021-12-14  15

    不少航空公司都会提供优惠的会员服务,当某顾客飞行里程累积达到一定数量后,可以使用里程积分直接兑换奖励机票或奖励升舱等服务。现给定某航空公司全体会员的飞行记录,要求实现根据身份证号码快速查询会员里程积分的功能。

    输入格式:

    输入首先给出两个正整数NN\le 10^5105)和KK\le 500500)。其中KK是最低里程,即为照顾乘坐短程航班的会员,航空公司还会将航程低于KK公里的航班也按KK公里累积。随后NN行,每行给出一条飞行记录。飞行记录的输入格式为:18位身份证号码(空格)飞行里程。其中身份证号码由17位数字加最后一位校验码组成,校验码的取值范围为0~9和x共11个符号;飞行里程单位为公里,是(0, 15 000]区间内的整数。然后给出一个正整数MM\le 10^5105),随后给出MM行查询人的身份证号码。

    输出格式:

    对每个查询人,给出其当前的里程累积值。如果该人不是会员,则输出No Info。每个查询结果占一行。

    输入样例:

    4 500 330106199010080419 499 110108198403100012 15000 120104195510156021 800 330106199010080419 1 4 120104195510156021 110108198403100012 330106199010080419 33010619901008041x

    输出样例:

    800 15000 1000 No Info

    思路分析:考查散列,使用map会超时。利用链接分离法解决冲突。

    #include <cstdio> #include <cstdlib> #include <string.h> typedef struct node { char id[20]; int len; struct node* next; } Node; typedef struct { int TableSize; Node* Table; } HashTable; int nextPrime( int n ) { while( 1 ) { bool flag = true; for( int i = 2; i < n; i++ ) { if( n % i == 0 ) { flag = false; break; } } if( flag ) { break; } n++; } return n; } HashTable* createHashTable( int n ) { HashTable* H = ( HashTable* )malloc( sizeof( HashTable ) ); H->TableSize = nextPrime( n ); H->Table = ( Node* )malloc( ( H->TableSize ) * sizeof( Node ) ); for( int i = 0; i < H->TableSize; i++ ) { H->Table[i].next = NULL; H->Table[i].id[0] = '\0'; H->Table[i].len = 0; } return H; } int Hash( HashTable* H, char key[] ) { int index = 0; for( int i = 13; i <= 17; i++ ) { if( key[i] == 'x' ) { index = index * 10 + 10; } else { index = index * 10 + key[i] - '0'; } } return index; } Node* Find( HashTable* H, char key[] ) { int index = Hash( H, key ) % ( H->TableSize ); Node* ptr = H->Table[index].next; while( ptr && strcmp( ptr->id, key ) ) { ptr = ptr->next; } return ptr; } void Insert( HashTable* H, char key[], int l ) { Node* p = Find( H, key ); if( !p ) { //printf( "没找到\n" ); Node* newNode = ( Node* )malloc( sizeof( Node ) ); int index = Hash( H, key ) % ( H->TableSize ); newNode->next = H->Table[index].next; H->Table[index].next = newNode; strcpy( newNode->id, key ); newNode->len = l; } else { //printf( "找到了\n" ); p->len = p->len + l; } } int main() { //freopen( "123.txt", "r", stdin ); int n, k; scanf( "%d%d", &n, &k ); HashTable* H = createHashTable( n ); char id[20]; int l; //printf( "%d\n", H->TableSize ); for( int i = 0; i < n; i++ ) { scanf( "%s %d", id, &l ); if( l < k ) l = k; Insert( H, id, l ); } scanf( "%d", &n ); for( int i = 0; i < n; i++ ) { scanf( "%s", id ); Node* p = Find( H, id ); if( !p ) { printf( "No Info\n" ); } else { printf( "%d\n", p->len ); } } return 0; }

    转载请注明原文地址: https://ju.6miu.com/read-968967.html

    最新回复(0)