hnust oj 问题C:查找

总结:本题要用点数据结构,或者高效的查找算法,再注意多组数据输入输出时的效率即可。(cin,cout效率远不及scanf,printf)

1.使用set :

#include<bits/stdc++.h>
using namespace std;
#define endl "\n"
int main()
{
    ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
    set<int>a;
    int n,m;
    while(cin>>n>>m)
    {
        while(n--)
        {
            int x;
            cin>>x;
            a.insert(x);
        }
        while(m--)
        {
            int y;
            cin>>y;
            if(a.find(y)!=a.end())
               cout<<"yes"<<endl;
            else 
               cout<<"no"<<endl;
        }
        a.clear();
    }
    return 0;
}

2.用二分查找:

#include<bits/stdc++.h>
using namespace std;
#define Ios ios::cync_with_stdio(0),cin.tie(0),cout.tie(0);
#define endl '\n'
const int N=100005;

int main()
{
	int n,m;
	
	while(scanf("%d%d",&n,&m)!=EOF)
	{
	vector<int>a;
		for(int i=1;i<=n;i++)
		{
			int x;
			scanf("%d",&x);
			a.push_back(x);
		}
       sort(a.begin(),a.end());
		for(int i=1;i<=m;i++)
		{
			int x;
			scanf("%d",&x);
			if(*(lower_bound(a.begin(),a.end(),x))==x)
		     printf("yes\n");
			else 
		 printf("no\n");
		}
	}
   return 0;
}

3.模拟哈希表:

#include<bits/stdc++.h>
using namespace std;
const int N=1e5;
const int mod=1e5;
typedef struct {
   vector<int>a;
}point;

int H(int x)
{
   if(x<0)
   x=-x;
   return x%mod;
}

int main()
{
  int n,m;
  while(scanf("%d%d",&n,&m)!=EOF)
  {
     point s[N];
     int x;
     for(int i=1;i<=n;i++)
     {
       scanf("%d",&x);
        int h=H(x);
        s[h].a.push_back(x);
       // cout<<"1234532\n";
     }
     for(int i=0;i<N;i++)
     {
        if(s[i].a.size())
        sort(s[i].a.begin(),s[i].a.end());
     }
     for(int i=1;i<=m;i++)
     {
        scanf("%d",&x);
        
        int h=H(x);
       if(find(s[h].a.begin(),s[h].a.end(),x)!=s[h].a.end())
       printf("yes\n");
        else 
        printf("no\n");
     }
  
  }
  
   return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值