1.描述:
Raju and Meena love to play with Marbles. They have got a lot of marbles with numbers written on them. At the beginning, Raju would place the marbles one after another in ascending order of the numbers written on them. Then Meena would ask Raju to find the first marble with a certain number. She would count 1…2…3. Raju gets one point for correct answer, and Meena gets the point if Raju fails. After some fixed number of trials the game ends and the player with maximum points wins. Today it’s your chance to play as Raju. Being the smart kid, you’d be taking the favor of a computer. But don’t underestimate Meena, she had written a program to keep track how much time you’re taking to give all the answers. So now you have to write a program, which will help you in your role as Raju.
2. 输入:
There can be multiple test cases. Total no of test cases is less than 65.
Each test case consists begins with 2 integers: N the number of marbles and Q the number of queries Mina would make. The next N lines would contain the numbers written on the N marbles. These marble numbers will not come in any particular order. Following Q lines will have Q queries. Be assured, none of the input numbers are greater than 10000 and none of them are negative.
Input is terminated by a test case where N=0 and Q=0.
3.输出:
For each test case output the serial number of the case.
For each of the queries, print one line of output. The format of this line will depend upon whether or not the query number is written upon any of the marbles. The two different formats are described below:
‘x found at y’, if the first marble with number x was found at position y. Positions are numbered 1,2,…,N.
‘x not found’, if the marble with number x is not present.
Look at the output for sample input for details.
4.样例输入:
4 1 2 3 5 1 5 5 2 1 3 3 3 1 2 3 0 0
5.样例输出:
CASE# 1: 5 found at 4 CASE# 2: 2 not found 3 found at 3
6.题目大意:
多组数据,每组数据第一行给出数据个数N和查询次数Q,给出数据要按升序排序,根据查找情况输出;
7.思路
用vector处理,排序用sort,查找可以用lower_bound,注意使用不同方法的耗时;
8.代码
#include<bits/stdc++.h> using namespace std; vector<int>ve; int n,m;//n组数据,m次询问 int t,q;//t是具体数据,q是查询数据 int cnt;//组号 int main() { while(cin>>n>>m) { if(n==0||m==0) return 0; printf("CASE# %d:\n",++cnt); ve.clear(); for(int i=1;i<=n;i++) { scanf("%d",&t); ve.push_back(t); } sort(ve.begin(),ve.end()); for(int i=1;i<=m;i++) { scanf("%d",&q); int s=lower_bound(ve.begin(),ve.end(),q)-ve.begin();//找到要查找数据的下标 if(ve[s]==q) { printf("%d found at %d\n",q,s+1); } else { printf("%d not found\n",q); }//比较数据是否相同 } } }
9.反思
因为 lower_bound 是返回下标,所以检查相不相同只需比较此下标位置的元素和查询元素的大小是否相等即可
最开始我检查元素这个元素存不存在用的count()函数,count()函数需要遍历整个容器,效率比较低,我又换成了find() 函数,但是效率都不如直接下标查询快(count函数超时,find函数400ms,下标访问100ms),注意恰当方法。
if(find(ve.begin(),ve.end(),q)==ve.end()) { printf("%d not found\n",q); } else { int s=lower_bound(ve.begin(),ve.end(),q)-ve.begin()+1; printf("%d found at %d\n",q,s); }
10.STL 函数库
自己总结的模板函数和用法,持续更新