Lower Bound-STL

来源:互联网 发布:软件测试周末班 编辑:程序博客网 时间:2024/06/15 00:44

Lower Bound-STL

You are given integers in the sorted order. Then you are given queries. In each query you will be given an integer and you have to tell whether that integer is present in the array, if so you have to tell at which index it is present and if it is not present you have to tell the index at which the smallest integer that is just greater than the given number is present.
Lower bound is a function that can be used with a sorted vector.

Input Format

The first line of the input contains the number of integers . The next line contains integers in sorted order. The next line contains , the number of queries. Then lines follow each containing a single integer .
If the same number is present multiple times, you have to print the first index at which it occurs.
The input is such that you always have an answer for each query.

Constraints

,where is element in the array.

Output Format

For each query you have to print "Yes"(without the quotes)if the number is present and at which index(1-based) it is present separated by a space.
If the number is not present you have to print "No"(without the quotes) followed by the index of the next smallest number just greater than that number.
You have to output each query in a new line.

Sample Input

 8

 1 1 2 2 6 9 9 15

 4

 1

 4

 9

 15

Sample Output

 Yes 1

 No 5

 Yes 6

 Yes 8

 

百度翻译:

按排序顺序给出整数。然后给你一些疑问。在每个查询中,你将得到一个整数,你必须判断数组中是否存在整数,如果是这样的话,你必须告诉它存在哪个索引,如果它不存在,你必须告诉最小的整数大于给定数字的索引。

 

下界是一个可以与排序向量一起使用的函数。了解如何使用下限来解决这个问题,点击这里。

 

输入格式

 

输入的第一行包含整数。下一行包含按顺序排序的整数。下一行包含查询的数量。然后行跟随每一个包含一个整数。

 

如果同一个数字出现多次,则必须打印出现的第一个索引。

 

输入是这样的,所以每个查询都有一个答案。

 

约束

 

数组中的元素在哪里?。

 

输出格式

 

对于每个查询你要打印“是”(没有引号)如果数字出现在哪些指标(1)它是用空格隔开。

 

如果数字不存在,你必须打印“否”(没有引号),后面是下一个最小值的索引,大于那个数字。

 

您必须在一行中输出每个查询。

 

 

#include <cmath>

#include <cstdio>

#include <vector>

#include <iostream>

#include <set>

#include <map>

#include <algorithm>

using namespace std;

int main()

{

   int m,num;

   cin >> m;

   vector<int> v;

   for (int i=0; i<m; i++)

   {

       cin >> num;

       v.push_back(num);

   }

   int n, val;

   cin >> n;

   for (int i=0; i<n; i++)

   {

       cin >> val;

       vector<int>::iterator low = lower_bound(v.begin(), v.end(), val);

       if (v[low - v.begin()] == val)

           cout << "Yes " << (low - v.begin()+1) << endl;

       else

           cout << "No " << (low - v.begin()+1) << endl;

   }

   return 0;

}

原创粉丝点击