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

O(n)的单调栈454ms

Posted by 511818218 at 2013-10-10 16:41:07 on Problem 2452
#include<cstdio>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<cmath>
using namespace std;
struct node{int low,high,id1,id2;}p,stack[50055];
int i,ans,top,x,n;
int main()
{
	while(~scanf("%d",&n))
	{
		top=ans=0;
		for(i=1;i<=n;i++)
		{
			scanf("%d",&x);	
			if(x>stack[top].high&&top)
			{
				while(x>stack[top].high&&top)p=stack[top--],ans=max(ans,p.id2-p.id1);
				p.high=x,p.id2=i,stack[++top]=p;
			}
			else if(x<stack[top].low&&top)
			{
				while(x<stack[top].low)p=stack[top--],ans=max(ans,p.id2-p.id1);
				p.low=p.high=x,p.id1=p.id2=i,stack[++top]=p;
			}
			else
			{
				p.low=p.high=x,p.id1=p.id2=i,stack[++top]=p;
				stack[++top]=p;
			}
		}
		while(top)p=stack[top--],ans=max(ans,p.id2-p.id1);
		printf(!ans?"-1\n":"%d\n",ans);
	}
} 

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