最大距离(二分 栈 思维)

给出一个长度为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
这个题目困扰了好久,不知道从哪儿下手。这是一个贪心没错了。但是怎么贪心。。无奈搜了搜题解。原来使用二分找小于等于val的最小位置。
代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;

const int maxx=5e4+10;
int a[maxx];
int b[maxx];
int n;
int k=0;

int findpos(int x)//二分找到小于等于这个数最小的位置
{
	int l=0;
	int r=k-1;
	int mid;
	while(l<r)
	{
		mid=(l+r)/2;
		if(a[b[mid]]>x)
		l=mid+1;
		else if(a[b[mid]]<x)
		r=mid;
		else return b[mid];
	}
	return b[l];
}

int main()
{
	while(scanf("%d",&n)!=EOF)
	{
		int ans=0;
		k=0;
		for(int i=0;i<n;i++)
		scanf("%d",&a[i]);
		for(int i=0;i<n;i++)
		{
			if(k==0||a[b[k-1]]>a[i])//维护一个单调递减的栈
			b[k++]=i;
			else
			{
				int pos=findpos(a[i]);
				ans=max(ans,i-pos);
			}
		}
		printf("%d\n",ans);
	}
	return 0;
}

个人认为,这种方法不好理解,我现在也没怎么理解这个,下面介绍一种简单的方法。
使用结构体排序,一遍就过了。
代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;

const int maxx=5e4+10;
struct node{
	int num;
	int pos;
}p[maxx];
int cmp(const node &a,const node &b)
{
	if(a.num!=b.num)
	return a.num<b.num;
	else return a.pos<b.pos;
}
int n;

int main()
{
	while(scanf("%d",&n)!=EOF)
	{
		for(int i=0;i<n;i++)
		{
			scanf("%d",&p[i].num);
			p[i].pos=i;
		}
		sort(p,p+n,cmp);
		int tmp=p[0].pos;
		int ans=0;
		for(int i=1;i<n;i++)
		{
			if(p[i].pos>tmp) ans=max(ans,p[i].pos-tmp);
			else tmp=p[i].pos;
		}
		printf("%d\n",ans);
	}
}

自己多多理解。
努力加油a啊,(o)/~

猜你喜欢

转载自blog.csdn.net/starlet_kiss/article/details/83048611