zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    vue中使用第三方UI库的移动端rem适配方案
    前端规范--eslint standard
    从上往下打印二叉树
    栈的压入,弹出序列
    随机森林
    LR
    顺时针打印矩阵
    包含min函数的栈
    树的子结构
    合并两个有序链表
  • 原文地址:https://www.cnblogs.com/Gaomez/p/14004157.html
Copyright © 2011-2022 走看看