您的位置:首页 > 其它

POJ 2452 Sticks Problem

2014-11-04 11:23 351 查看
RMQ+二分。。。。
枚举 i  ,找比 i 小的第一个元素,再找之间的第一个最大元素。。。。。

 

                  Sticks Problem

Time Limit: 6000MS Memory Limit: 65536K
Total Submissions: 9338 Accepted: 2443
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
 
 

1 #include <iostream>
2 #include <cstdio>
3 #include <cstring>
4
5 using namespace std;
6
7 int dp_max[60000][16],dp_min[60000][16],a[60000],n;
8
9 int _max(int l,int r)
10 {
11     if(a[l]>=a[r]) return l;
12     else return r;
13 }
14
15 int _min(int l,int r)
16 {
17     if(a[l]<=a[r]) return l;
18     else return r;
19 }
20
21 void Init()
22 {
23     for(int i=1;i<=n;i++)
24         dp_max[i][0]=dp_min[i][0]=i;
25     for(int j=1;(1<<j)<=n;j++)
26     {
27         for(int i=1;i+(1<<j)-1<=n;i++)
28         {
29             int m=i+(1<<(j-1));
30             dp_max[i][j]=_max(dp_max[i][j-1],dp_max[m][j-1]);
31             dp_min[i][j]=_min(dp_min[i][j-1],dp_min[m][j-1]);
32         }
33     }
34 }
35
36 int rmq_min(int L,int R)
37 {
38     int k=0;
39     while(L+(1<<k)-1<=R) k++; k--;
40     return _min(dp_min[L][k],dp_min[R-(1<<k)+1][k]);
41 }
42
43 int rmq_max(int L,int R)
44 {
45     int k=0;
46     while(L+(1<<k)-1<=R) k++; k--;
47     return _max(dp_max[L][k],dp_max[R-(1<<k)+1][k]);
48 }
49
50 int main()
51 {
52     while(scanf("%d",&n)!=EOF)
53     {
54         for(int i=1;i<=n;i++)
55             scanf("%d",a+i);
56         Init();
57         int ans=0,r,k;
58         for(int i=1;i+ans<n;i++)
59         {
60             int low=i+1,high=n,mid;
61             while(low<=high)
62             {
63                 if(low==high) break;
64                 mid=(low+high)>>1;
65                 if(a[i]<a[rmq_min(low,mid)])
66                     low=mid+1;
67                 else
68                     high=mid;
69             }
70             r=low;
71             k=rmq_max(i,r);
72             if(a[i]<a[k])
73                 ans=max(ans,k-i);
74         }
75         if(ans==0) printf("-1\n");
76         else printf("%d\n",ans);
77     }
78     return 0;
79 }


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: