当前位置: 代码迷 >> 综合 >> POJ 2452 Sticks Problem(贪心做法非RMQ)
  详细解决方案

POJ 2452 Sticks Problem(贪心做法非RMQ)

热度:88   发布时间:2024-01-12 20:42:43.0

题目链接:

http://poj.org/problem?id=2452

这道题目是咋RMQ分类里面看到的,但是感觉之前用贪心做过,ran然后试了试(过了)

可能是数据太水了吧

这是RMQ做法的网址:https://blog.csdn.net/u013480600/article/details/21904107

Sticks Problem

Time Limit: 6000MS   Memory Limit: 65536K
Total Submissions: 11461   Accepted: 3082

Description

Xuanxuan has n sticks of different length. One day, she puts all her sticks in a line, represented by S1, S2, S3, ...Sn. After measuring the length of each stick Sk (1 <= k <= n), she finds that for some sticks Si and Sj (1<= i < j <= n), each stick placed between Si and Sj is longer than Si but shorter than Sj. 

Now given the length of S1, S2, S3, …Sn, you are required to find the maximum value j - i.

Input

The input contains multiple test cases. Each case contains two lines. 
Line 1: a single integer n (n <= 50000), indicating the number of sticks. 
Line 2: n different positive integers (not larger than 100000), indicating the length of each stick in order.

Output

Output the maximum value j - i in a single line. If there is no such i and j, just output -1.

Sample Input

4
5 4 3 6
4
6 5 4 3

Sample Output

1
-1

Source

POJ Monthly,static

题目大意:

题目实质上求区间[l,r]内,所有数的都小于s[r],都大于s[r],,,,

然后输出r-l的值

思路:

直接贪心(O(n))的时间

co

 

从第i(i初始位1)个开始寻找,找后面比开始那个大于的数,并记录位置cnt(注意更新),

直到出现比最开始小的数,计算ans=max(ans,cnt-i),,,,,,,(ans的初始值位-1)(如果没有,就直接可以输出ans)

然后从i=cnt+1;开始继续下一个寻找,直接到最后(自习想一想为什么可以直接从i=cnt+1开始,而不是简单的i++;

然后最后输出ans

This is the code:

#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<iostream>
#include<iomanip>
#include<list>
#include<map>
#include<queue>
#include<sstream>
#include<stack>
#include<string>
#include<set>
#include<vector>
using namespace std;
#define PI acos(-1.0)
#define EPS 1e-8
#define MOD 1e9+7
#define LL long long
#define ULL unsigned long long     //1844674407370955161
#define INT_INF 0x7f7f7f7f      //2139062143
#define LL_INF 0x7f7f7f7f7f7f7f7f //9187201950435737471
// ios::sync_with_stdio(false);
// 那么cin, 就不能跟C的 scanf,sscanf, getchar, fgets之类的一起使用了。
const int dr[]={0, 0, -1, 1, -1, -1, 1, 1};
const int dc[]={-1, 1, 0, 0, -1, 1, -1, 1};
int a[50005];
int main()
{int n;while(~scanf("%d",&n)){for(int i=1;i<=n;++i)scanf("%d",&a[i]);int ans=-1;for(int i=1;i<n;++i){if(a[i+1]>a[i])//满足最基本的条件,有至少一个比a[i]大{int maxn=a[i+1];//记录最大值int cnt=i+1;//记录位置for(int j=i+2;j<=n;++j)//寻找{if(a[j]>maxn)//更新{maxn=a[j];cnt=j;}else if(a[j]<a[i])//结束break;}ans=max(ans,cnt-i);//寻找更符合题意的答案i=cnt;//不是cnt+1的,因为后面接着要i++}}printf("%d\n",ans);}return 0;
}

 

 

 

 

 

  相关解决方案