logo AlgoBeat OnlineJudge
登录 注册

鸡题解

作者: Steven1356  ·  发布于 2026-08-12 8:39:10  ·  最后修改于 2026-08-12 18:20:14
已通过
审核员:AlgoBeat 官方账号 · 2026-08-12 18:20:14

找到最大值(鸡王)和最小值(鸡宝)的位置。

计算把它们移到目标位置所需的交换次数。

如果最大值在最小值左边,移动时不会相互影响。

如果最大值在最小值右边,它们会"擦肩而过",需要减去一次重复计算的交换。

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    int n;
    cin >> n;
    
    vector<int> a(n);
    int maxPos = 0, minPos = 0;
    
    for (int i = 0; i < n; i++) {
        cin >> a[i];
        if (a[i] > a[maxPos]) maxPos = i;
        if (a[i] < a[minPos]) minPos = i;
    }
    
    // 计算把最大值移到位置0所需的交换次数
    int swaps = maxPos;
    
    // 计算把最小值移到位置n-1所需的交换次数
    // 注意:如果最小值在最大值左边,移动最大值时会影响最小值的位置
    if (minPos > maxPos) {
        // 最大值在最小值左边,互不影响
        swaps += (n - 1 - minPos);
    } else {
        // 最大值在最小值右边(或同一个位置,但题目保证体重互不相同)
        // 移动最大值时,最小值会向左移动一位
        // 所以最小值到末尾的距离要减1
        swaps += (n - 1 - minPos - 1);
    }
    
    cout << swaps << endl;
    
    return 0;
}

暂无评论

登录 后即可评论。