zoukankan      html  css  js  c++  java
  • 51nod 1268最大距离

    题目来源: Codility
    基准时间限制:1 秒 空间限制:131072 KB 分值: 20 难度:3级算法题
     收藏
     关注
    给出一个长度为N的整数数组A,对于每一个数组元素,如果他后面存在大于等于该元素的数,则这两个数可以组成一对。每个元素和自己也可以组成一对。例如:{5, 3, 6, 3, 4, 2},可以组成11对,如下(数字为下标):
    (0,0), (0, 2), (1, 1), (1, 2), (1, 3), (1, 4), (2, 2), (3, 3), (3, 4), (4, 4), (5, 5)。其中(1, 4)是距离最大的一对,距离为3。
    Input
    第1行:1个数N,表示数组的长度(2 <= N <= 50000)。
    第2 - N + 1行:每行1个数,对应数组元素Ai(1 <= Ai <= 10^9)。
    Output
    输出最大距离。
    Input示例
    6
    5
    3
    6
    3
    4
    2
    Output示例
    3


    遍历每个数ai,求右边比ai大的最远的位置。排序+后缀。先排序,然后第i个后面都是比第i个大的,然后求i-n中下标的最大值行。
     1 #include <bits/stdc++.h>
     2 #define ll long long
     3 using namespace std;
     4 const int N = 5e4+10;
     5 int pre[N], n;
     6 struct Nod{
     7     int num,id;
     8 }nod[N];
     9 bool cmp(Nod &a, Nod &b) {
    10     if(a.num != b.num) return a.num < b.num;
    11     else return a.id < b.id;
    12 }
    13 int main() {
    14     cin >> n;
    15     for(int i = 1; i <= n; i ++) {
    16         cin >> nod[i].num;
    17         nod[i].id = i;
    18     }
    19     sort(nod+1,nod+1+n,cmp);
    20     pre[n] = nod[n].id;
    21     for(int i = n-1; i > 0; i --) {
    22         pre[i] = max(pre[i+1],nod[i].id);
    23     }
    24     int MAX = 0;
    25     for(int i = 1; i < n; i ++) {
    26         MAX = max(MAX, pre[i+1]-nod[i].id);
    27     }
    28     cout << MAX << endl;
    29     return 0;
    30 }
  • 相关阅读:
    Codeforces Round #380(div 2)
    Codeforces Round #378(div 2)
    Codeforces Round #379(div 2)
    CCPC2016合肥现场赛
    CCPC2016沈阳站
    HDU2222 Keywords Search__AC自动机
    poj2185Milking Grid
    POJ2961_kmp
    POJ 2406
    poj 2752Seek the Name, Seek the Fame
  • 原文地址:https://www.cnblogs.com/xingkongyihao/p/8976777.html
Copyright © 2011-2022 走看看