51nod 1272 最大距离贪心/单调栈

 

          (1)题目大大意就是寻找一个(arr[i],arr[j]),(j>i&&arr[j]>arr[i])求(j-i)的最大值

          (2)贪心思路,见代码1

          (3)思路1维护一个单调递减的栈,如果发现此时的arr[i]小于此时栈顶元素,或者栈为空那么进,else(不二分最后一组数据会超时,)二分查找栈(数组模拟)中的第一个比此时元素小的下标更新ans.

        (1)代码

#include <algorithm>
#include <stdio.h>
#include <stack>
#include <istream>
#include <map>
#include <math.h>
#include <iostream>
#include <queue>
#include <string.h>
#include <set>
#include <cstdio>
#define MAX 2005
using namespace std;
const int maxn = 10000007;

 

struct arr {
int val;
int id;
}inof[maxn];
bool cmp(arr a, arr b) {
if (a.val != b.val)return a.val>b.val;
return a.id > b.id;

}
int main() {
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &inof[i].val);
inof[i].id = i;
}
int ans = 0,ec = -9999;
sort(inof, inof + n,cmp);
for (int i = 0; i < n; i++) {
if (inof[i].id > ec)ec = inof[i].id;
else if(ec>inof[i].id)ans = max(ans, ec - inof[i].id);
//printf("%d **** %d\n",ec,inof[i].id);
}
cout << ans << endl;
return 0;
}

(2)代码

 

 

include <stdio.h>
#include <algorithm>
using namespace std;

int b[50000],a[50000];
int n,q;
int findpos(int val) //找到小于等于val的数的最小下标
{
int lo = 0, hi = q - 1, mid;
while (lo < hi)
{
mid = (hi+lo)/2;
if (a[b[mid]] < val)
hi = mid;
else if (a[b[mid]] > val)
lo = mid + 1;
else
return b[mid];
}
return b[lo];
}
int main() {
int i, pos, ans = 0;
scanf("%d", &n);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
for (i = 0; i < n; i++)
{
if (0 == q || a[b[q-1]] > a[i]) //单调减
b[q++] = i;
else {
pos = findpos(a[i]);
ans = max(ans, i - pos);
}
}
printf("%d\n", ans);
return 0;
}

 

posted @ 2018-04-10 23:40  Xzavieru  阅读(152)  评论(0编辑  收藏  举报