442C

贪心

感觉思路很奥妙 首先我们把那些比两边小的数删掉,因为不删的话两边的数就会选这个数,这样就成了先上升后下降的序列,很明显除了第一第二大的数都能选,然后统计就好了。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 500010;
int n, top;
ll ans;
ll a[N], st[N];
int main()
{
    scanf("%d", &n);
    for(int i = 1; i <= n; ++i) 
        scanf("%lld", &a[i]);
    for(int i = 1; i <= n; ++i) 
    {
        while(top > 1 && st[top - 1] >= st[top] && st[top] <= a[i]) 
        {
            ans += min(a[i], st[top - 1]);
            --top;
        }
        st[++top] = a[i];    
    }
    sort(st + 1, st + top + 1);
    for(int i = 1; i < top - 1; ++i) ans += st[i];
    printf("%lld
", ans);
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/19992147orz/p/7152959.html