UVA10474 marble Where Where is the Marble?

UVA10474 marble Where Where is the Marble?




Translation of the meaning of problems
existing N marble, wrote a non-negative integer on each marble. First, the respective number of small to large order, then Q answer questions. Each question asks whether there is a marble that says some integer x, if so, on which even answer that says x marble. Marble is sorted from left to right No. 1 ~ N.
Sample input and output:

//输入
4 1     4个大理石      1个问题
2        2 3 5 1 大理石上写的数字
3         
5
1
5     这个5是问题      是否有一个大理石写着5     
5 2
1
3
3
3
1
2
3
0 0
//输出
CASE# 1:
5 found at 4       注意一定要先排序再判断是第几个     2351  => 1 2 3 5 所以第四个
CASE# 2:
2 not found
3 found at 3

So this question is the key to determine the sort plus x is the first of several
topics meaning is very clear: to sort, search again. Using the algorithm header file sort and lower_bound easily do both
for finding
binary_search (): As the name suggests, binary search, but this function has a very TD question, its return value is of type bool, and provided there is container sequence.

Here is its description: "binary_search trying to find value in the sorted elements of [first, last) if there is an equivalent [first, last) to the inner element value, it will return true, otherwise returns false, it does not return. Find location "

lower_bound ():
.. "lower_bound () which tries to find elements in the sorted value [first, last) if [first, last) having a value equivalent to the elements, lower_bound returns an iterator to point wherein if the first element there is no such element exists, it will return to assume that such an element exists, there will be a position "

Mutt is:. "Points to the first element is not less than the value of any element if the value is greater than [First, last) is, last return"
For example: 1 2 3 5 4 Q not there, returns with lower_bound is not less than the first position of the pointer 4 so that the determination needs to be determined a [p] == x

#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
const int maxn=10000;
using namespace std;
int main()
{
	int n,q;
	int x;
	int a[maxn];
	int kase=0;
	while(cin>>n>>q&&n)
	{
		for(int i=0;i<n;i++)
		{
			cin>>a[i];
		}
		sort(a,a+n); //排序
		while(q--)
		{
			cin>>x;       //要问的那个整数 
			int p=lower_bound(a,a+n,x)-a; //记录位置,注意:这个函数(对于数组)返回的是那个数的指针,你要减掉数组的指针,才能得到int,(指针相减)
			cout<<(++kase)<<"# :";
			if(a[p]==x) printf("%d found at %d\n", x, p+1);    //判断
			else printf("%d not found\n", x);
		} 
	}
	return 0;
} 

Guess you like

Origin www.cnblogs.com/serendipity-my/p/12641003.html