nyoj138 找球号(二)_离散化

找球号(二)

时间限制:1000 ms  |  内存限制:65535 KB
难度:5
 
描述
在某一国度里流行着一种游戏。游戏规则为:现有一堆球中,每个球上都有一个整数编号i(0<=i<=100000000),编号可重复,还有一个空箱子,现在有两种动作:一种是"ADD",表示向空箱子里放m(0<m<=100)个球,另一种是"QUERY”,表示说出M(0<M<=100)个随机整数ki(0<=ki<=100000100),分别判断编号为ki 的球是否在这个空箱子中(存在为"YES",否则为"NO"),先答出者为胜。现在有一个人想玩玩这个游戏,但他又很懒。他希望你能帮助他取得胜利。
 
输入
第一行有一个整数n(0<n<=10000);
随后有n行;
每行可能出现如下的任意一种形式:
第一种:
一个字符串"ADD",接着是一个整数m,随后有m个i;
第二种:
一个字符串"QUERY”,接着是一个整数M,随后有M个ki;

输出
输出每次询问的结果"YES"或"NO".
样例输入
2
ADD 5 34 343 54 6 2
QUERY 4 34 54 33 66
样例输出
YES
YES
NO
NO
来源
[苗栋栋]原创
上传者
苗栋栋
解题思路:这个题有n(<10000)组命令,每个命令最多一百个数,所有至少需要1000000个数需要存储,所以把需要存储的数字%1000000后作为存储位置的下标。
数据结构采用链地址法处理冲突。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

typedef struct node{
    int a;
    node *next;
};
node *ball[1000005];

void storage(int temp){
    int c=temp%1000000;
    node *p;
    p=ball[c]->next;
    //if(p!=NULL){
    //    p=new node;
    //    p->a=temp;
    //    p->next=NULL;
    //}else{
        p=new node;
        p->a=temp;
        p->next=ball[c]->next;
        ball[c]->next=p;
    //}
}

int judge(int temp){
    int c=temp%1000000;
    node *p;
    p=ball[c]->next;
    while(p){
        if(p->a==temp){
            return 1;
        }
        p=p->next;
    }
    return 0;
}

int main()
{
    int n;
    for(int i=0;i<1000000;i++){
        ball[i]=new node;
        ball[i]->next=NULL;
    }
    scanf("%d",&n);
    for(int j=0;j<n;j++){
        char instru[10];
        int m;
        int temp;

        scanf("%s",instru);
        if(instru[0]=='A'){

            scanf("%d",&m);
            for(int i=0;i<m;i++){
                scanf("%d",&temp);
                storage(temp);
            }
        }else{
            scanf("%d",&m);
            for(int i=0;i<m;i++){
                scanf("%d",&temp);
                int yorn=judge(temp);
                if(yorn==1){
                    printf("YES
");
                }else{
                    printf("NO
");
                }
            }
        }



    }
    return 0;
}
原文地址:https://www.cnblogs.com/TWS-YIFEI/p/5817168.html