zoukankan      html  css  js  c++  java
  • P6503 [COCI2010-2011#3] DIFERENCIJA 题解

    Link

    P6503 [COCI2010-2011#3] DIFERENCIJA

    Solve

    这道题和SP10622相类似

    我们可以把最大值和最小值分开来考虑,于是对于每个(a[i]),我们统计出(a[i])作为最大值和最小值的范围,从而算出(a[i])对答案的贡献

    (preunderline{~}min)表示前面第一个比(a[i])小的,(nxtunderline{~}min)表示后面第一个比(a[i]小的),那么(a[i])作为(max)的范围就是(preunderline{~}min+1~nxtunderline{~}min-1)(pre)(nxt)数组用单调栈很容易处理出来,对答案的贡献就是((i-preunderline{~}min) ast (nxtunderline{~}max-i)ast a[i])

    计算(min)的时候同理

    Code

    #include<bits/stdc++.h>
    using namespace std;
    typedef long long LL;
    const int maxn=300005,INF=1<<30;
    int N,pre_min[maxn],pre_max[maxn],nxt_min[maxn],nxt_max[maxn],top,c[maxn];
    LL ans;
    struct AS{
    	int x,id;
    }a[maxn],p[maxn];
    inline int read(){
    	int ret=0,f=1;char ch=getchar();
    	while(ch<'0'||ch>'9'){if(ch=='-')f=-f;ch=getchar();}
    	while(ch<='9'&&ch>='0')ret=ret*10+ch-'0',ch=getchar();
    	return ret*f;
    }
    int main(){
    	freopen("diferencija.in","r",stdin);
    	freopen("diferencija.out","w",stdout);
    	N=read();
    	for(int i=1;i<=N;i++)a[i].x=read(),a[i].id=i;
    	p[top=1]=(AS){0,0};for(int i=1;i<=N;i++){while(top>0&&p[top].x>=a[i].x)top--;pre_min[i]=p[top].id;p[++top]=a[i];}
    	p[top=1]=(AS){INF,0};for(int i=1;i<=N;i++){while(top>0&&p[top].x<=a[i].x)top--;pre_max[i]=p[top].id;p[++top]=a[i];}
    	p[top=1]=(AS){0,N+1};for(int i=N;i;i--){while(top>0&&p[top].x>a[i].x)top--;nxt_min[i]=p[top].id;p[++top]=a[i];}
    	p[top=1]=(AS){INF,N+1};for(int i=N;i;i--){while(top>0&&p[top].x<a[i].x)top--;nxt_max[i]=p[top].id;p[++top]=a[i];}
    	for(int i=1;i<=N;i++){ans+=((LL)(nxt_max[i]-i)*(i-pre_max[i])-(LL)(nxt_min[i]-i)*(i-pre_min[i]))*(LL)a[i].x;}
    	printf("%lld
    ",ans);
    	return 0;
    }
    
  • 相关阅读:
    Python3 之 列表推导式
    python3 之 趣味数学题(爱因斯坦)
    python3 之 判断闰年小实例
    python3 之 判断字符串是否只为数字(isdigit()方法、isnumeric()方法)
    116.Populating Next Right Pointers in Each Node
    115.Distinct Subsequences
    114.Flatten Binary Tree to Linked List
    113.Path Sum II
    112.Path Sum
    111.Minimum Depth of Binary Tree
  • 原文地址:https://www.cnblogs.com/martian148/p/13886497.html
Copyright © 2011-2022 走看看