"Bzoj 1345" [Baltic2007] sequence problem sequence

Source: Internet
Author: User

1345: [Baltic2007] sequence problem sequence time limit: 5 Sec Memory Limit: 162 MB
Submit: 618 Solved: 307
[Submit] [Status] [Discuss] Description for a given sequence A1, ..., an, we do an operation on it. reduce (i), which replaces the elements AI and ai+1 in the sequence with an element, Max (ai,ai+1), to get a new sequence shorter than the original sequence. The cost of this operation is Max (ai,ai+1). After n-1 the operation, you can get a sequence of length 1. Our task is to calculate the lowest cost of the reduce operation step, turning the given sequence into a sequence of length 1. Input first behaves as an integer n (1 <= n <= 1,000,000) representing the length of a given sequence. The next n rows, one integer for each line of AI (0 <=ai<= 1, 000, 000, 000), are the elements in the sequence. Output has only one row, an integer, and the minimum cost of turning the sequence into an element. Sample Input3
1
2
3Sample Output5

HINT

30% of test Data n<=500;
50% of the test data N <= 20,000.



Monotone queue.


Each number must be merged with the smaller of the first number on both sides of him that is larger than he, and the direct monotone queue O (n) does.


#include <iostream> #include <algorithm> #include <cstring> #include <cstdlib> #include < Cstdio> #define LL Long long#define inf 1000000005#define M 1000000+5using namespace Std;int a[m],q[m],n,s[m];int Main ( {    scanf ("%d", &n), for (int i=1;i<=n;i++) scanf ("%d", &a[i]), s[i]=inf;q[1]=a[1];int r=1;for (int i=2;i <=n;i++) {while (R>=1&&a[i]>q[r]) r--;if (R) s[i]=q[r];while (R>=1&&q[r]==a[i]) r--;q[++r ]=a[i];} r=1;q[1]=a[n];for (int i=n-1;i;i--) {while (R>=1&&a[i]>q[r]) r--;if (R) s[i]=min (S[i],q[r]), while (r> =1&&q[r]==a[i]) r--;q[++r]=a[i];} LL ans=0;for (int i=1;i<=n;i++) if (S[i]!=inf) Ans+=s[i];cout<<ans<<endl;return 0;}



"Bzoj 1345" [Baltic2007] sequence problem sequence

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.