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;
}