NYOJ86找球号(一)

题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=86


这道题两种解法,一个是二分查找,一个是用set。


注意:这道题数据不是读到文件尾,超时的小伙伴看过来。   


二分:

 

#include <cstdio>
#include <algorithm>

using namespace std;

const int maxn = 1e8;
int a[1000000 + 5];
int m,n;
void b_search(int key)

{
    int left = 0;
    int right = m - 1;
    int flag = 0;
    while(left < right)
    {
        int mid = (left + right) / 2;
        if(a[mid] == key)
        {
            flag = 1;
            printf("YES\n");
            break;
        }
        else if(a[mid] > key)
            right = mid - 1;
        else if(a[mid] < key)
            left = mid + 1;
    }
    if(!flag)
    {
        printf("NO\n");
    }
}
int main()
{
    scanf("%d%d",&m,&n);
    for(int i = 0; i < m; ++i)
        scanf("%d",&a[i]);
    sort(a,a + m);
    for(int i = 0; i < n; ++i)
    {
        int t ;
        scanf("%d",&t);
        if(t > maxn)
        {
            printf("NO\n");
            continue;
        }
        b_search(t);
    }
    return 0;
}
        

set:
#include <cstdio>
#include <set>

using namespace std;

set<int> ans;

int main()
{
    int m,n;
    scanf("%d%d",&m,&n);
    int t;
    for(int i = 0; i < m; ++i)
    {
        scanf("%d",&t);
        if(!ans.count(t))
            ans.insert(t);
    }
    for(int i = 0; i < n; ++i)
    {
        scanf("%d",&t);
        if(ans.count(t))
            printf("YES\n");
        else
            printf("NO\n");
    }
    return 0;
}



你可能感兴趣的:(二分查找,排序,ACM,STL)