UVA 10474 Where is the Marble(stl,sort)

UVA 10474 Where is the Marble
题目:题目意思就是给出两个数m和n下面输入m个数,再依次输入n个数,查找n个数在前面的m个数中是第几大
思路很简单,排序加查找(也可以二分优化)。
方法一:用哈希,先排序,排好序之后看跟前一个是否一样,然后哈希一下,就OK了

#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;
int a[10005],hashs[10005];
int main()
{
    int x,n,q;
    int cases=1;
    while(cin>>n>>q)
    {
        if(n==0&&q==0)
            break;
        memset(a,-1,sizeof(a));
        memset(hashs,-1,sizeof(hashs));
        for(int i=0;i<n;i++)
        {
            cin>>a[i];
        }
        sort(a,a+n);
        hashs[a[0]]=1;
        for(int i=1;i<n;i++)
        {
            if(a[i]!=a[i-1])
            {
                hashs[a[i]]=i+1;
            }
        }
         cout<<"CASE# "<<cases++<<":"<<endl;
        for(int i=1;i<=q;i++)
        {
            cin>>x;
            if(hashs[x]!=-1)
            {
                cout<<x<<" found at "<<hashs[x]<<endl;
            }
            else
            {
                cout<<x<<" not found"<<endl;
            }
        }
    }
    return 0;
}

方法二:用二分查找的upper_bound函数,和lower_bound函数
upper_bound函数:int pos1=upper_bound(a,a+n,x)-a; pos1即为在a数组里第一个大于等于数x的位置
lower_bound函数:int pos2=upper_bound(a,a+n,x)-a; pos2即为在a数组里第一个大于数x的位置
用两个函数同时找x的位置,如果能够位置相同,那么证明x不在a数组里,否则的话pos2+1即为x的位置因为lower_bound是从0开始计算位置的

#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;

int main()
{
    int n,q,x;
    int a[10005];
    ios::sync_with_stdio(false);
    int cases=1;
    while(cin>>n>>q)
    {
        if(n==0&&q==0)
            break;
            //cout<<100<<endl;
        int qq=q;

        cout<<"CASE# "<<cases++<<":"<<endl;
        //cout<<cases
       // while(qq--)
        {
            memset(a,0,sizeof(a));
            for(int i=0; i<n; i++)
            {
                cin>>a[i];
                // b[i]=a[i];
            }
            sort(a,a+n);
            for(int i=1; i<=q; i++)
            {

                cin>>x;
                /*for(int i=0; i<n; i++)
                    cout<<a[i]<<" ";
                cout<<endl;*/
                int pos1=upper_bound(a,a+n,x)-a;
                int pos2=lower_bound(a,a+n,x)-a;
                //cout<<pos1<<"*****"<<pos2<<endl;
                if(pos1==pos2)
                {
                    cout<<x<<" not found"<<endl;
                }
                else
                {
                    cout<<x<<" found at "<<pos2+1<<endl;
                }
            }

        }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值