【贪心】P4995 跳跳!
题目
思路
由于下午打了一波LIS板子所以,直接写了一波类似最大子序列和的DP然后WA。重看一遍题发现要求经过所有节点,也就是可以往回跳,而且每个节点要经过一次
其实就是按照某种排序后相邻差值绝对值最大。那么如何排序呢?
原本按照一般排序贪心尝试交换然后看差值,结果发现涉及三项还是四项,没法通过简单的排序解决
然后观察式子,考虑单步,两个数差值平方最大就选择最小和最大的。然后困扰我的是如何连续贪心,看了一波题解意识到自己是如此愚笨。只需要依次选择最大,剩余数的最小,剩余数的最大……即可
代码
// Problem: P4995 跳跳!
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P4995
// Memory Limit: 125 MB
// Time Limit: 1000 ms
// FishingRod
//
// Powered by CP Editor (https://cpeditor.org)
#include<bits/stdc++.h>
using namespace std;
#define endl "\n"
typedef long long LL;
typedef pair<int,int> PII;
/*DATA & KEY
*/
int T;
const int N=305;
LL h[N];
void solve()
{
//NEW DATA CLEAN
//NOTE!!!
int n;cin>>n;
for(int i=1;i<=n;i++)cin>>h[i];
sort(h+1,h+1+n);
LL ans=h[n]*h[n];
LL last=h[n];
int l=1,r=n-1;
for(int i=2;i<=n;i++)
{
if(i%2==0)
{
ans+=(last-h[l])*(last-h[l]);
last=h[l];
l++;
}
else
{
ans+=(h[r]-last)*(h[r]-last);
last=h[r];
r--;
}
}
cout<<ans;
}
//36 9 4e
int main()
{
// scanf("%d",&T);
// while(T--)solve(T);
solve();
return 0;
}