CodeForces 601 B.Lipshitz Sequence(單調棧)__Code

來源:互聯網
上載者:User

Description
根據利普希茨條件定義一個長度為n的序列h的L(h)值:
n<2,L(h)=0;
n>=2,(1<=i< j<=n)
現給出一長度為n的序列a,給出q次查詢,每次查詢給出一個區間[l,r],求序列s={a[l],…,a[r]}的所有子序列L值之和
Input
第一行為兩個整數n和q表示序列長度和查詢次數,第二行n個整數ai表示這個序列,之後q行每行兩個整數l和r表示查詢區間(2<=n<=1e6,1<=q<=100,0<=ai<=1e8)
Output
對於每次查詢,輸出L(s)的值
Sample Input
10 4
1 5 2 9 1 3 4 2 1 7
2 4
3 8
7 10
1 9
Sample Output
17
82
23
210
Solution
設x1< x2< x3,y1< y2< y3,下面證明

不妨設,那麼我們有


所以一個序列的L(h)=max( |h[i+1]-h[i]| )(1<=i< n),那麼若求一個序列所有子序列L值之和,只需求出每個|h[i+1]-h[i]|的影響範圍即可[l,r](即在這個區間內|h[i+1]-h[i]|最大),那麼用單調棧即可解決這類問題
Code

#include<cstdio>#include<iostream>#include<algorithm>#include<cstring>using namespace std;#define maxn 111111typedef long long ll;int n,q,a[maxn],b[maxn],s[maxn],top,L[maxn],R[maxn],l,r,len;int main(){    while(~scanf("%d%d",&n,&q))    {        for(int i=1;i<=n;i++)scanf("%d",&a[i]);        while(q--)        {            scanf("%d%d",&l,&r);            len=r-l;            for(int i=l;i<r;i++)                b[i-l+1]=abs(a[i]-a[i+1]);            top=0;            for(int i=1;i<=len;i++)            {                while(top&&b[i]>=b[s[top]])top--;                L[i]=top==0?0:s[top];                s[++top]=i;            }               top=0;            for(int i=len;i>=1;i--)            {                while(top&&b[i]>b[s[top]])top--;                R[i]=top==0?len+1:s[top];                s[++top]=i;            }            ll ans=0;            for(int i=1;i<=len;i++)                ans+=1ll*(i-L[i])*(R[i]-i)*b[i];            printf("%I64d\n",ans);        }    }    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.