zoukankan      html  css  js  c++  java
  • codeforces 442C C. Artem and Array(贪心)

    题目链接:

    C. Artem and Array

    time limit per test
    2 seconds
    memory limit per test
    256 megabytes
    input
    standard input
    output
    standard output

    Artem has an array of n positive integers. Artem decided to play with it. The game consists of n moves. Each move goes like this. Artem chooses some element of the array and removes it. For that, he gets min(a, b) points, where a and b are numbers that were adjacent with the removed number. If the number doesn't have an adjacent number to the left or right, Artem doesn't get any points.

    After the element is removed, the two parts of the array glue together resulting in the new array that Artem continues playing with. Borya wondered what maximum total number of points Artem can get as he plays this game.

    Input

    The first line contains a single integer n (1 ≤ n ≤ 5·105) — the number of elements in the array. The next line contains n integers ai(1 ≤ ai ≤ 106) — the values of the array elements.

    Output

    In a single line print a single integer — the maximum number of points Artem can get.

    Examples
    input
    5
    3 1 5 2 6
    output
    11
    input
    5
    1 2 3 4 5
    output
    6
    input
    5
    1 100 101 100 1
    output
    102

    题意:

    给出n个数,每次删去一个数,得到的分数是min(a,b),a和b是这个左右相邻的数,边界上的数不能删去,现在要求怎么样才能得到最大的得分;

    思路:

    贪心的想,每次如果一个数不小于它相邻的两个数,那么这个数就可以删去,得到的分数就是min(a,b),最后剩下的就是一个倒v形状的或者一半,最高的那两个选不了,再把剩下的相加就好了;

    AC代码:

    #include <bits/stdc++.h>
    using namespace std;
    typedef long long LL;
    const int maxn=5e5+10;
    int n,a[maxn],q[maxn];
    
    int main()
    {
        scanf("%d",&n);
        for(int i=1;i<=n;i++)scanf("%d",&a[i]);
        LL ans=0;
        q[1]=a[1];int p=1;
        for(int i=2;i<=n;i++)
        {
            while(q[p]<=a[i]&&q[p]<=q[p-1]&&p>1)
            {
                ans=ans+min(q[p-1],a[i]);
                p--;
            }
            q[++p]=a[i];
        }
        sort(q,q+p+1);
        for(int i=1;i<p-1;i++)ans=ans+q[i];
        cout<<ans<<endl;
    
        return 0;
    }
    

      

  • 相关阅读:
    vue导航守卫和axios拦截器的区别
    js中的深拷贝与浅拷贝
    Storyboard中拖拽控件不能运行的问题(在运行的时候,相应的控件代码没有被执行)
    关于stringWithFormat:
    两层嵌套的JSON包的解法
    button的action属性如果有参数,必须加“:”
    iOS 协同开发出fatal error: file 'XX-Prefix.pch' has been modified since the precompiled header was built
    [转] Objective-C语法快速参考
    iOS应用程序内存查看工具
    XCode快捷键大全
  • 原文地址:https://www.cnblogs.com/zhangchengc919/p/5942367.html
Copyright © 2011-2022 走看看