算法学习

时间:2019-04-20
本文章向大家介绍算法学习,主要包括算法学习使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

STL初步

排序和检索

题目:现有N个大理石,每个大理石上写了一个非负整数。首先把各数从小到大排序,然后回 答Q个问题。每个问题问是否有一个大理石写着某个整数x,如果是,还要回答哪个大理石上 写着x。排序后的大理石从左到右编号为1~N。(在样例中,为了节约篇幅,所有大理石上 的数合并到一行,所有问题也合并到一行。)
简化题目:n个数的数组和q个问题,问题是数组中是否有x,如果有则x在排序后数组中的位置
样例输入

4 1
2 3 5 1
5
5 2
1 3 3 3 1
2 3

样例输出

CASE #1:
5 found at 4
CASE #2:
2 no found
3 found at 3
#define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
#include <algorithm>
#define Max 10000
using namespace std;
int main()
{
 int a[Max];
 int n, q, kase = 1;
 while (scanf("%d%d", &n, &q) == 2 && n)
 {
  printf("CASE #%d", kase++);
  for (int i = 0; i < n; i++)
  {
   scanf("%d", &a[i]);
  }
  sort(a, a + n);
  while (q--)
  {
   int x;
   scanf("%d", &x);
   int result = lower_bound(a, a + n , x) - a;
   if (a[result] == x)
    printf("%d found at %d", x, result+1);
   else
    printf("no found");
  }
  
 }
 return 0;
}