nyoj 138 找球号(二)(哈希)

题目:nyoj——138

/***
哈希求解。。。采用链表保存
插入时,可以去除重复
查找 找到该组,然后在改组的查找
当这个组不存在时或是没有找到时是 NO  其他是YES
1e6+1 时间最短
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define N 1000001;

typedef struct numb
{
    int a;
    numb *next;
}numb;


numb *head[1000005];

void insert(int x)
{
    int ans = x % N;
    if(head[ans] == NULL)
    {
        head[ans] = (numb *) malloc(sizeof(numb));
        head[ans]->next = NULL;
        head[ans]->a = -1;
    }

    numb *p;
    p = head[ans];
    int flag = 1;
    while(p->next != NULL)
    {
        if(p->next->a == x)
        {
            flag = 0;
            break;
        }
        p = p ->next;
    }
    numb *q;
    if(flag)
    {
        q = (numb *) malloc (sizeof(numb));
        q -> a = x;
        q->next = NULL;
        p->next = q;
        p = q;
    }
}

int find(int x)
{
    int ans = x % N;
    numb *p;
    if(head[ans] == NULL)
        return 0;
    else
    {
        p = head[ans]->next;
        while(p != NULL)
        {
            if(p->a == x)
                return 1;
            p = p->next;
        }
        return 0;
    }
}
int main()
{
    int T;
    scanf("%d",&T);
    char ch[12];
    int x,t;
    while(T--)
    {
     scanf("%s",ch);
     if(ch[0] == 'A')
        {
            scanf("%d",&t);
            while(t--)
            {
                scanf("%d",&x);
                insert(x);
            }
        }
    else
    {
        scanf("%d",&t);
            while(t--)
            {
                scanf("%d",&x);
                if(find(x) == 1)
                    printf("YES\n");
                else
                    printf("NO\n");
            }
    }
    }
    return 0;
}

 

posted @ 2013-08-21 09:56  heity  阅读(257)  评论(0编辑  收藏  举报