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)复杂度,为何会超时呢?附代码

Posted by 987654OPK at 2013-12-25 16:14:59 on Problem 2796
#include <iostream>
#include <stack>
#include <cstdio>
using namespace std;
#define MAXN 100010
int n,l,r;
long long int sum[MAXN],ans,result=-1;
struct Node
{
	int index;
    int value;
}node[MAXN],tmp,tmp1;
stack<Node> st;
int main()
{
	tmp.index=0;
	tmp.value=-1;
	st.push(tmp);
	while(scanf("%d",&n)!=EOF)
	{
		result=-1;
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&node[i].value);
			node[i].index=i;
			sum[i]=sum[i-1]+node[i].value;
		}
		for(int i=1;i<=n;i++)
		{
			while(node[i].value<st.top().value)
			{
				tmp=st.top();st.pop();
				tmp1=st.top();
				ans=tmp.value*(sum[i-1]-sum[tmp1.index]);
				if(ans>result)
				{
					result=ans;
					l=tmp1.index+1;
					r=i-1;
				}
			}
			st.push(node[i]);
		}
		while(st.top().index!=0)
		{
			tmp=st.top();st.pop();
			tmp1=st.top();
			ans=tmp.value*(sum[n]-sum[tmp1.index]);
			if(ans>result)
			{
				result=ans;
				l=tmp1.index+1;
				r=n;
			}
		}
		printf("%lld\n%d %d\n",result,l,r);
	}
	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