成绩查询(哈希表)

录入 n 个学生的成绩,并查询。
★数据输入
第一行输入包括 nm(1<=n<=50,000,1<=m<=100,000)两个数字。
接下来 n ,每行包含名字和成绩,名字用字符串表示,长度不超过 4.成绩为不
超过 100 的非负整数,名字仅由小写字母组成。
接下来 m ,每行包括一个名字。
★数据输出
输出 m ,如果查询的学生不存在,输出”not,exist!”,否则输出学生的成绩。

not,exist!
85
80
not,exist!


★提示
n 个名字各不相同
60%的数据
1<=n,m<=2,000
100%的数据
1<=n<=50,000,1<=m<=100,000

 

#include <stdio.h>  
#include <iostream>  
#include <algorithm> 
#include <math.h>  
#include <map> 
#include <string>  
using namespace std;
struct Student{
    __int64 hash;
    int val;
}stu[200007];

bool cmp(Student a,Student b) 
{
    return a.hash < b.hash;    
}
int Lower_bound(int size, int key)
{
    int first = 0, middle;
    int half, len;
    len = size;

    while(len > 0) {
        half = len >> 1;
        middle = first + half;
        if(stu[middle].hash < key) {     
            first = middle + 1;          
            len = len-half-1;       //在右边子序列中查找
        }
        else
            len = half;            //在左边子序列(包含middle)中查找
    }
    return first;
}
int main()
{
    int n,m,i,j,val;
    __int64 hash;
    int a[5]={10001,1,1167388,321};
    string name;
    scanf("%d %d",&n,&m);
    for(i=0;i<n;i++)
    {
        cin>>name;
        scanf("%d",&val);
        hash = 0;
        for(j=0;j<name.size();j++)
        {
            hash += (name[j]-'0')*a[j];
        }
        stu[i].hash = hash;
        stu[i].val = val;
    } 
    sort(stu,stu+n,cmp);
    for(i=0;i<m;i++)
    {
        cin>>name;
        hash = 0;
        for(j=0;j<name.size();j++)
        {
            hash += (name[j]-'0')*a[j];
        }
        int pos = Lower_bound(n,hash);
        if (pos == n || stu[pos].hash != hash) puts("not,exist!");
        else printf("%d\n", stu[pos].val);
    } 
    return 0;
}
        

 

posted @ 2017-12-16 21:04  萌新上路  阅读(372)  评论(0编辑  收藏  举报