洛谷P4995 跳跳!题解
本题做法
- 贪心+排序+双指针 two-pointers。
思路
对于这道题,我们不难发现,当每次跳跃的 \(|h_i-h_j|\) 越大,最后消耗的体力值就越多。
我们可以使用双指针,一个指向开头(即 \(l=1\)),另一个指向结尾(即 \(r=n\))。进行循环 \(i:1\sim n\) 次,当 \(i\bmod{2}=1\) 时,代表需要向右跳,则
ans+=pow(a[r]-a[p],2)
if(i!=1) l++;
当 \(i\bmod{2}=0\) 时,代表需要向左跳,则
ans+=pow(a[l]-a[p],2);
r--;
最后输出 \(ans\) 即可。
代码
#include <bits/stdc++.h>
#define endl '\n'
#define ll long long
using namespace std;
const int INF = 0x3f3f3f3f;
const double EPS = 1e-8;
const int N = 305;
ll n, ans, a[N];
int main() {
cin >> n;
for (int i = 1; i <= n; i++) cin >> a[i];
sort(a + 1, a + 1 + n, greater<ll>());
int p = 0, l = 1, r = n;
for (int i = 1; i <= n; i++) {
if (i % 2 == 1) {
ans += pow(a[p] - a[l], 2);
p = l;
if (i != 1) r--;
} else {
ans += pow(a[p] - a[r], 2);
p = r;
l++;
}
}
cout << ans << endl;
return 0;
}

浙公网安备 33010602011771号