原题where is the marble?
现有N个大理石,每个大理石上写着一个非负整数。首先把各数从小到大排序,然后回答Q个问题。每个问题问是否有一个大理石写着某个整数x,是就回答哪个大理石上写着x。排序后的大理石从左向右编号为1-n。
input:
4 1
2 3 5 1
5
5 2
1 3 3 3 1
2 3
ouput:
CASE# 1:
5 found at 4
CASE# 2:
2 found at 3
代码如下:
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn=10000;
int main()
{
int n,q,x,a[maxn],kase=1;
while(cin>>n>>q)
{
cout<<"CASE# "<<kase++<<endl;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
sort(a,a+n); //sort函数可以完成排序,不局限于int型,默认从小到大,想换成从大到小需要外加一个函数
for(int i=0;i<n;i++)
{
cout<<a[i]<<endl;
}
while(q--)
{
cin>>x;
int p=lower_bound(a,a+n,x)-a; //lower_bound()可以查找大于或等于x的第一个位置
if(a[p]==x)
cout<<x<<" is found at "<<p+1<<endl;
und."<<endl;
}
}
return 0;
}
关于排序,c++中的sort函数可以很方便的完成任务,而且不局限于int型,需要头文件中的al
gorithm,lower_bound()可以查找大于或等于x的第一个位置,用法参考代码,同样在摸索中。
参考《算法竞赛入门经典》