码迷,mamicode.com
首页 > 其他好文 > 详细

51nod 1272 最大距离

时间:2018-05-18 01:20:16      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:更新   数字   else   bool   color   排序   algorithm   max   bsp   

给出一个长度为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
输出最大距离。

把每个数的数和序号关联起来,遍历一遍,从小到大排序,如果后边的数比前边的序号大或相等,就序号相减求最大,否则把前面的数更新为目前这个数。
#include <iostream>
#include <math.h>
#include <algorithm>
#include <stdio.h>
using namespace std;
struct node{
    int num,a;
}in[50005];

bool cmp(node x,node y)
{
    if(x.a==y.a) return x.num<y.num;
    return x.a<y.a;
}
int main()
{
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
    {
        cin>>in[i].a;
        in[i].num=i;
    }
    sort(in,in+n,cmp);
    int m=in[0].num,ans=0;
    for(int i=0;i<n;i++)
    {
        if(in[i].num>=m) ans=max(ans,in[i].num-m);
        else m=in[i].num;
    }
    cout<<ans<<endl;
}
 

 

51nod 1272 最大距离

标签:更新   数字   else   bool   color   排序   algorithm   max   bsp   

原文地址:https://www.cnblogs.com/fantastic123/p/9054079.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!