跳到正文

题解

题解:P11309 纷飞的樱花雨

zhangzirui66约 2 分钟
原文
文章信息与版本

文章信息

发布
2024年12月29日
收录
2025年12月12日
更新
2026年11月8日
篇幅
约 2 分钟
题目
P11309

版本

  1. v1当前

一道小分讨。

坑点在于交换可以不相邻且不能自己交换。

观察到只要 k≥1k \ge 1 就一定能将最大值换到最前面,剩下的随便换就行。但 n=2n=2 是例外,此时没有剩余可交换的,手动特判 kk 的奇偶性即可。

若 k=0k=0,则直接计算答案。

整合即可得出代码:

C++
#include<bits/stdc++.h>
using namespace std;
long long t, n, k, a[100005];
int main(){
	cin >> t;
    while(t --){
        cin >> n >> k;
        for(long long i = 1; i <= n; i ++) cin >> a[i];
        if(n == 2){//特判 n = 2
            if(k & 1){//奇数相当于换一次
                swap(a[2], a[1]);
                if(a[1] > a[2]) cout << a[1] * 2 << "\n";
                else cout << a[1] + a[2] << "\n";
                continue;
            }
            else{//反之相当于没换
                if(a[1] > a[2]) cout << a[1] * 2 << "\n";
                else cout << a[1] + a[2] << "\n";
                continue;
            }
        }
        if(k != 0){//最大值换到最前面
            long long maxn = 0;
            for(long long i = 1; i <= n; i ++) maxn = max(maxn, a[i]);
            cout << maxn * n << "\n";
        }
        else{//无法操作,直接计算
            long long sum = 0, maxn = 0;
            for(long long i = 1; i <= n; i ++) maxn = max(maxn, a[i]), sum += maxn;
            cout << sum << "\n";
        }
    }
	return 0;
}
原文