版权声明:本人原创,未经许可,不得转载 https://blog.csdn.net/qq_42505741/article/details/83116194
题目:
给出一个长度为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
输出最大距离。
Sample Input
6 5 3 6 3 4 2
Sample Output
3
解题报告:直觉就是暴力走一番啊,谁叫大力会出奇迹呢。奈何自己年轻,T了,确实5e4^2的复杂度不小了,然后就转换了思维,打算开结构体去排序。(因为暑假训练接触了这种题目,记住了复杂度比较小的操作),但是自己做的时候傻了,居然直接用结构体sort之后的位置去减之前的位置,二者有啥关系啊,当时真的是失了智了。后来参考了题解,发现自己的想法只是在大路上跑偏了一丢丢,就是找之后位置之前比它大的数目,即之前那个数字之后比它大的数目。如果遇到位置比它还在前的就更新一下,去寻找更大的距离。
ac代码:
扫描二维码关注公众号,回复:
3646420 查看本文章
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
#include<queue>
#include<vector>
using namespace std;
struct node{
int pos;
int val;
};
const int maxn = 50000+105;
struct node num[maxn];
bool cmp(node a,node b)
{
if(a.val!=b.val)
return a.val<b.val;
return a.pos<b.pos;
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
for(int i=0;i<n;i++)
scanf("%d",&num[i].val),num[i].pos=i;
sort(num,num+n,cmp);
int res=0;
int index=num[0].pos;
for(int i=0;i<n;i++)
{
res=max(res,num[i].pos-index);
if(num[i].pos-index<0)
index=num[i].pos;
}
printf("%d\n",res);
}
}