P4995 跳跳! 贪心

P4995 跳跳!

比较直白的贪心.

 

 

结论是每次跳跃都选择高度差最大的石头.给出粗略证明.

首先,把地面看成高度为0的石头,将所有石头按照高度升序排列为:

0, h1, h2, h3, ... , hn 则对于:

第一次跳跃,起点为0,终点为hi(1<=i<=n),最大值为(hn-0)2

第二次跳跃,起点非0,终点为1~n,最大值为(hn-h1)2

第三次跳跃,对于所有可能的起点和终点,可能的最大值为(hn-1-h2)2

...

并且以上所有最大值可同时取得.则有让你在排序后的石头之上反复横跳的策略.


实际上这只是在依靠直觉,具体的证明是需要摆出式子来的.见此题解

#include <algorithm>
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;

int n, h[310];
long long ans;

int main()
{
    cin >> n;
    h[0] = 0;
    for(int i = 1; i <= n; i++)
        cin >> h[i];
    sort(h, h + n + 1);

    int pos = -1, head = 0, end = n;
    while(n--)
    {
        ans += (h[end] - h[head]) * (h[end] - h[head]);
        if(pos == -1)
            head++;
        else
            end--;
        pos *= -1;
    }

    printf("%lld", ans);

    return 0;
}

 

posted @ 2020-11-19 19:46  goverclock  阅读(189)  评论(0)    收藏  举报