P4995. 跳跳!

考点

  • 贪心

题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

const int LEN = 350;

int arr[LEN];

ll cost(int l, int r)
{
return pow(arr[r] - arr[l], 2);
}

int main()
{
int n;
cin >> n;
for (int i = 1; i <= n; ++i)
cin >> arr[i];
sort(arr + 1, arr + n + 1);
int l = 0, r = n, dir = 1;
ll ans = 0;
while (l < r)
{
ans += cost(l, r);
if (dir)
++l;
else
--r;
dir ^= 1;
}
cout << ans;
return 0;
}

思路

基础的贪心题,每次从较小的跳到较大的,再从较大的跳到较小的即可