HDU-5805-NanoApe Loves Sequence(水题)

本文提供了一道来自HDU ACM在线评测系统的题目解析——编号5805的问题解答。该题旨在求解去掉数组中一个元素后,剩余相邻元素差的最大值的期望值。通过维护数组中的前三大量来实现高效求解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

链接:http://acm.hdu.edu.cn/showproblem.php?pid=5805

题意:给出一个数组,求去掉1个数字后相邻两数字差的最大值的期望*n,

题解:就是求去掉每个数字后相邻两数差最大值的和,笨笨的维护下前三大值就好;


#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 1e5+7;
int Scan()
{
    int res=0,ch,flag=0;
    if((ch=getchar())=='-')flag=1;
    else if(ch>='0'&&ch<='9')res=ch-'0';
    while((ch=getchar())>='0'&&ch<='9')res=res*10+ch-'0';
    return flag?-res:res;
}
void Out(int a)
{
    if(a>9)Out(a/10);
    putchar(a%10+'0');
}
int a[maxn];
int main()
{
    int T;
    scanf("%d",&T);
    int n,m;
    // long long ans=0;
    while(T--)
    {
        int Max=0,Max2=0,Max3=0;
        scanf("%d",&n);
        // int c=0;
        for(int i=0; i<n; ++i)
        {
            scanf("%d",&a[i]);
            if(i>0)
            {
                int p=abs(a[i]-a[i-1]);
                if(p>Max)
                {
                    Max3=Max2;
                    Max2=Max;
                    Max=p;

                  //  c=0;
                }
                else if(p>Max2)
                {
                    Max3=Max2;
                    Max2=p;
                }
                else if(p>Max3)
                {
                 Max3=p;
                }
                // if(p=Max)c++;
            }
        }
      //  cout<<Max<<" "<<Max2<<" "<<Max3<<endl;
        long long ans=0;
        if(abs(a[1]-a[0])==Max && Max2!=Max)ans+=Max2;
        else ans+=Max;
        if(abs(a[n-1]-a[n-2])==Max && Max2!=Max)ans+=Max2;
        else ans+=Max;
        for(int i=1; i<n-1; ++i)
        {
            int x=abs(a[i+1]-a[i]);
            int y=abs(a[i]-a[i-1]);
            int z=abs(a[i+1]-a[i-1]);
            if(x<y)swap(x,y);
            if(z>=Max)
            {
                ans+=z;
            }
            else if(x==Max && y==Max2)
            {
                ans+=max(Max3,z);
            }
            else if(x==Max)
            {
                ans+=max(Max2,z);
            }
            else
            {
                ans+=Max;
            }
        }
        cout<<ans<<endl;
    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值