NYOJ-138 找球号(二) (哈希)

原题链接:传送门

这道题我最开始是用的map标记来写的,但写完后发现TLE了,后来看别人的题解才知道是要用哈希来做,就学了一下哈希。但还是不太明白,为啥map标记会超时??


这里贴个用map写的TLE了的代码。。

#include <iostream>
#include <cstring>
#include <cstdio>
#include <map>
using namespace std;
map<int,int> M;

int main() {
    int t;
    char str[8];
    scanf("%d",&t);
    while(t--) {
        int n,x;
        scanf("%s %d",str,&n);
        if(str[0] == 'A') {
            for(int i=0; i<n; i++) {
                scanf("%d",&x);
                M[x] = 1;
            }
        } else {
            for(int i=0; i<n; i++) {
                scanf("%d",&x);
                if(M[x] == 1) {
                    printf("YES\n");
                } else printf("NO\n");
            }
        }
    }

    return 0;
}


AC代码:

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int N = 1000002;
const int fib = 100001;     //尽量是个稍微大一点的素数,以随机散列 

int Hash[N],Head[N],Next[N];        //Head相当于每个哈希表的头节点,Next指向当前节点的下一个节点 
int top;

void Add(int x) {
    int key = x % fib;
    Next[top] = Head[key];      //关键就是这。可以手动模拟一下。 
    Head[key] = top;
    Hash[top] = x;
    top ++;
}

bool Query(int x) {
    int key = x % fib;
    for(int i=Head[key]; i>-1; i=Next[i]) {     //如果有多个数散射后的特征值相同,会接着往下找 
        if(Hash[i] == x) {
            return true;
        }
    }
    return false;
}

int main() {
    int t,n,x;
    char str[8];
    scanf("%d",&t);
    memset(Head,-1,sizeof(Head));

    top = 0;
    while(t--) {
        scanf("%s %d",str,&n);
//      scanf("%d",&n);
        if(str[0] == 'A') {
            for(int i=0; i<n; i++) {
                scanf("%d",&x);
                Add(x);
            }
        } else {
            for(int i=0; i<n; i++) {
                scanf("%d",&x);
                if(Query(x)){
                    printf("YES\n");
                }
                else printf("NO\n");
            }
        }
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值