zoukankan      html  css  js  c++  java
  • ACM训练,大理石在哪儿?

    int p = lower_bound(a, a+num, x) - a; //在已排序数组a中查找大于或等于x的第一个位置

    lower_bound( )返回的是一个迭代器,-a相当于减去a的首地址,返回的p即是它们之间的距离。

    关于此函数的使用样例:

    一个数组number序列为:4,10,11,30,69,70,96,100.(注:number为数组名)

     

    pos = lower_bound( number, number + 8, 4) - number,pos = 0.即number数组的下标为0的位置。
    pos = lower_bound( number, number + 8, 10) - number, pos = 1,即number数组的下标为1的位置。
    pos = lower_bound( number, number + 8, 100) - number, pos = 7,即number数组的下标为7的位置。

    sort(a, a + N);    //  将 N 个数字升序排列 

    加上头文件后在数组中可以直接使用,a为数组名,N为数组长度。

    两个函数都使用到的头文件:#include <algorithm>

    外加 using namespace std;

    ···完整代码如下

    #include <cstdio>
    #include <algorithm>
    using namespace std;
    const int maxNum = 10005;
    int main() {
        // N个大理石,Q个问题,qu猜测数字
        // a存放数字
        int N, Q, x,a[maxNum], kase = 0;
        while(scanf("%d%d", &N, &Q) == 2 && N) {
            printf("CASE# %d:
    ", ++kase);  // kase对样例记号,排序 
            for(int i = 0; i < N; i++) {
                scanf("%d", &a[i]);     // 存在数组中,数组大小为N 
            }
            // 排序
            sort(a, a + N);    //  将 N 个数字升序排列 
            while(Q--) {    //  Q代表查几次 
                scanf("%d", &x);    //  x 是要查找的数字 
                int p = lower_bound(a, a + N, x) - a;// lower_bound(a, a + N, x)             
                if(a[p] == x) {                      // 在已排序数组a中查找大于或等于x的第一个位置
                    printf("%d found at %d
    ", x, p + 1);
                } else {
                    printf("%d not found
    ", x);
                }
            }
        } 
        return 0;
    }


    ---------------------
    作者:MissXy_
    来源:CSDN
    原文:https://blog.csdn.net/MissXy_/article/details/76736215

  • 相关阅读:
    DataGridView编辑后立即更新到数据库的两种方法
    DataTable 转换成 Json的3种方法
    C# 应用程序配置文件App.Config和web.config
    C#中使用JsonConvert解析JSON
    C#JsonConvert.DeserializeObject反序列化json字符
    WIN10远程桌面、常用命令
    control[控制面板]的参数
    win10企业版变成win10专业版的设置教程
    DLL加密
    微信小程序顶部tab
  • 原文地址:https://www.cnblogs.com/epep/p/10904837.html
Copyright © 2011-2022 走看看