`

南阳理工OJ 86 找球号(一)外挂 哈希 字典树

 
阅读更多

 

 

/*
字典树
*/

#include<stdio.h>
#include<string.h>
#include<malloc.h>
struct node
{
	bool f;
	struct node*p[10];
}root;
void init(node *p)
{
	p->f=false;
	for(int i=0;i<10;i++)
		p->p[i]=NULL;
}
node * xin()
{
	node *p =(node*)malloc(sizeof(node));
	init(p);
	return(p);
}
void add(char *str)
{
	int n=strlen(str);
	node * p=&root;
	for(int i=0;i<n;i++)
	{
		if(p->p[str[i]-'0']==NULL)
			p->p[str[i]-'0']=xin();	
		p=p->p[str[i]-'0'];
	}
	p->f=true;
}
bool find(char *str)
{
	int n=strlen(str);
	node * p=&root;
	for(int i=0;i<n;i++)
	{
		if(p->p[str[i]-'0']==NULL)return false;
		p=p->p[str[i]-'0'];
	}
	return p->f;
}
int main()
{
	int m,n;
	char term[15];
	scanf("%d%d",&m,&n);
	init(&root);
	while(m--)
	{
		scanf("%s",term);
		add(term);
	}
	while(n--)
	{
		scanf("%s",term);
		if(find(term))printf("YES\n");
		else printf("NO\n");
	}
	return(0);
}

 

 

 

 

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int hash[3125100],n,m;
int main()
{
   // freopen("in.txt","r",stdin);
    scanf("%d %d",&n,&m);
//    memset(hash,0,sizeof(hash));
    int x,t,mod;
    char ch;
    for(int i=0; i<n; i++)
    {
        // scanf("%d",&x);
        x=0;
        while(!((ch=getchar())>='0'&&ch<='9'))
        {
        }
        x=(ch-'0');
        while((ch=getchar())>='0' && ch<='9')
            x=x*10+(ch-'0');
        t=x>>5;
        mod=x-(t<<5);
        hash[t]|=(1<<mod);
    }
    for(int i=0; i<m; i++)
    {
//            scanf("%d",&x);
        x=0;
        while(!((ch=getchar())>='0'&&ch<='9'))
        {
        }
        x=(ch-'0');
        while((ch=getchar())>='0' && ch<='9')
            x=x*10+(ch-'0');
        t=x>>5;
        mod=x-(t<<5);
        if(hash[t]&(1<<mod))
            printf("YES\n");
        else printf("NO\n");
    }
    return 0;
}

 

 

 

 

第二种方法用到了位运算,开不了那么多的int或者bool ,但可以开那么多的位,照样能存储一样的信息,

还有输入输出用到了getchar()用这个接收字符再算成整数 都比scanf 快的多!!!不信试试!

1
6
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics