最大距離(二分 棧 思維)
阿新 • • 發佈:2018-11-08
給出一個長度為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)/~