51nod 1272 最大距离

给出一个长度为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;
}
 

猜你喜欢

转载自www.cnblogs.com/fantastic123/p/9054079.html