题解016:P11908 [NHSPC 2023] G. 博物館
题目大意
有
思路
贪心。
为什么呢?题目中说,要将前
代码
#include <bits/stdc++.h>
using namespace std;
#define int long long
pair<int, int> a[100005];//定义,second是出现位置i
bool cmp(pair<int, int> x, pair<int, int> y) {//第一次排序,以ci为第一关键字,i为第二关键字排序
if (x.first == y.first)
return x.second < y.second;
return x.first > y.first;
}
bool cmp1(pair<int, int> x, pair<int, int> y) {//第二次排序,按i排序
return x.second < y.second;
}
signed main() {
int n, k, ans = 0;
cin >> n >> k;
for (int i = 1; i <= n; i++)
cin >> a[i].first, a[i].second = i;
sort(a + 1, a + n + 1, cmp);//排两次
sort(a + 1, a + k + 1, cmp1);
for (int i = 1; i <= k; i++)
ans += a[i].second - i;//计算总距离,即交换次数
cout << ans;
return 0;
}
AC 记录