算法与数据结构实验题 9.2 寻人启事

1、题目:

885534-20161120173951092-1645805516.png

2、AC代码:

#include<stdio.h>
#include<string.h>
#define size 1000003   //哈希表的长度,离1000000最近的素数  
#define n 6

struct Value{
    char *val;
    Value *next;
};

char name[size][n];
Value hash[size];

//计算hash值的算法 
int BKDRhash(char *s)
{
    int seed=131;
    __int64 hash =0;
    while(*s)
    {
        hash=hash*seed+(*s++);
    }
    return hash%size;
}

//查找是否存在相等的hash值  
bool Find(char *name)
{
    int t=BKDRhash(name);
    if(hash[t].val)
    {
        if(strcmp(name,hash[t].val)==0)//找到相等的hash值 
        {
            return true;
        }
        else
        {
            Value *v=hash[t].next;
            while(v)
            {
                if(strcmp(v->val,name)==0)
                return true;
                v=v->next; 
            }
        }
    }
    return false;
}


int main()
{
    int i,N,M,t;
    int ans=0;
    char str[6];
    Value *tmp;
    scanf("%d%d",&N,&M);
    for(i=0;i<size;i++)
    {
        hash[i].next=NULL;
        hash[i].val=NULL;
    }
    
    for(i=0;i<N;i++)    //实现插入 
    {
        scanf("%s",name[i]);
        t=BKDRhash(name[i]);
        if(hash[t].val==NULL)   //如果当前元素为空,则插入 
        {
            hash[t].val=name[i];
        }
        else    //若不为空,则插入到链表中 
        {
            tmp=new Value;
            tmp->val=name[i];
            tmp->next=hash[t].next;
            hash[t].next=tmp;
        }
    }
    //查找 
    for(i=0;i<M;i++)
    {
        scanf("%s",str);
        if(Find(str)==true)
        {
            ans++;
        }
    }
    printf("%d\n",ans);
    return 0;
}

3、一个TLE代码:

#include<stdio.h>
#include<string.h>
char name[1000001][10],str[1001][10];
int main()
{
    int n,m;
    scanf("%d%d",&n,&m);
    int i,j;
    int count=0;
    for(i=0; i<n; i++)
    {
        scanf("%s",name[i]);
    }
    for(j=0; j<m; j++)
    {
        scanf("%s",str[j]);
        for(i=0; i<n; i++)
        {
            if(strcmp(name[i],str[j])==0)
            {
                count++;
                break; 
            }
        }
    }
    printf("%d\n",count);
    return 0;
}

转载于:https://www.cnblogs.com/laixiaolian/p/6083028.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值