1. 程式人生 > >【51Nod - 1272】【最大距離】

【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

輸出最大距離。

Sample Input

6
5
3
6
3
4
2

Sample Output

3

解題報告:直覺就是暴力走一番啊,誰叫大力會出奇蹟呢。奈何自己年輕,T了,確實5e4^2的複雜度不小了,然後就轉換了思維,打算開結構體去排序。(因為暑假訓練接觸了這種題目,記住了複雜度比較小的操作),但是自己做的時候傻了,居然直接用結構體sort之後的位置去減之前的位置,二者有啥關係啊,當時真的是失了智了。後來參考了題解,發現自己的想法只是在大路上跑偏了一丟丟,就是找之後位置之前比它大的數目,即之前那個數字之後比它大的數目。如果遇到位置比它還在前的就更新一下,去尋找更大的距離。

ac程式碼:

#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);
	}
}