http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1272&judgeId=597187
题目来源: Codility
基准时间限制:1 秒 空间限制:131072 KB 分值: 20 难度:3级算法题
收藏
关注
给出一个长度为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
输出最大距离。
Input示例
6 5 3 6 3 4 2
Output示例
3
看到这道题使用单调栈...可是我不会,于是上网查了查单调栈,模仿学长的代码写了一份,可是用两个栈会超时卡在最后一组
#include<iostream>
#include<string.h>
#include<algorithm>
#include<stack>
#include<cstdio>
#define maxn 500100
#define clear(c,b) memset(c,b,sizeof(c))
struct node
{
int num;
int id;
}ac[maxn];
using namespace std;
int main()
{
stack <node> s_1,s_2;
int n;
//std:: cin>>n;
scanf("%d",&n);
int ans=0;
for(int i=0;i<n;i++)
{
ac[i].id=i;
//std:: cin>>ac[i].num;
scanf("%d",&ac[i].num);
if(s_1.size()==0||s_1.top().num>ac[i].num) //如果比栈里的元素小或者栈为空压进去
s_1.push(ac[i]);
else
{
while(s_1.top().num<=ac[i].num)//寻找比当前元素小的所有栈的元素
{
ans=max(ans,i-s_1.top().id);//用当前的位置减去之前压进去的比他小的元素的位置
s_2.push(s_1.top());//把之前的元素存起来
s_1.pop();//出栈
if(s_1.empty()) break;
}
while(!s_2.empty())
{
s_1.push(s_2.top());//从新把栈还原
s_2.pop();
}
}
}
printf("%d\n",ans);
//std:: cout<<ans<<endl;
return 0;
}
然后这就成了一道思维题............??大小先排好,找位置,大小往上走位置往上走才是我们应该找的数
#include<iostream>
#include<string.h>
#include<algorithm>
#include<stack>
#include<cstdio>
#define maxn 500100
#define clear(c,b) memset(c,b,sizeof(c))
using namespace std;
struct node
{
int num;
int id;
}ac[maxn];
int cmp(node a,node b)
{
if(a.num==b.num)return a.id<b.id;
return a.num<b.num;
}
int main()
{
int n;
cin>>n;
for(int i=0;i<n;i++)
{
ac[i].id=i;
cin>>ac[i].num;
}
sort(ac,ac+n,cmp);
int pos=0,maxx=0;
for(int i=0;i<n;i++)
{
if(i==0||ac[i].id<pos) pos=ac[i].id;
else maxx=max(ac[i].id-pos,maxx);
}
printf("%d\n",maxx);
//std:: cout<<ans<<endl;
return 0;
}