Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

【双单调栈】两次二分,N*log(N)*log(N) 610ms AC 附代码

Posted by WilliamACM at 2013-03-15 10:53:53 on Problem 2452
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <stack>
using namespace std;
const int N=5e4+9;
struct node
{
    int v,id;
}hi[N],low[N];
int n,a[N],hs,ht,ls,lt,ans;
int min_num(int id)
{
    int s=ls,t=lt;
    while(s<=t)
    {
        int mid=(s+t)>>1;
        if(low[mid].id>id) s=mid+1;
        else t=mid-1;
    }
    if(s>lt) return 0x7fffffff;
    return low[s].v;
}
void search(int s,int t,int p)
{
    while(s<=t)
    {
        int mid=(s+t)>>1;
        if(min_num(hi[mid].id)<=a[p]) s=mid+1;
        else t=mid-1;
    }
    ans=max(ans,hi[s].id-p);
}
void init()
{
    for(int i=0;i<n;i++) scanf("%d",&a[i]);
    ht=lt=0;
    hi[0].v=low[0].v=a[n-1];
    hi[0].id=low[0].id=n-1;
    ans=0;
    for(int i=n-2;i>=0;i--)
    {
        while(ht>=0&&hi[ht].v<=a[i])ht--;
        hi[++ht].v=a[i];
        hi[ht].id=i;
        search(hs,ht-1,i);

        while(lt>=0&&low[lt].v>=a[i]) lt--;

        low[++lt].v=a[i];
        low[lt].id=i;
    }
    printf("%d\n",ans?ans:-1);
}
int main()
{
    //freopen("in","r",stdin);
    while(scanf("%d",&n)!=EOF)
    {
        init();
    }
    return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator