给两个整数n, k (0 <= k <= n - 1)
问:打印出a[i + 1] > a[i](0<= i < n - 1)的次数等于k的方案.
解题思路
打个比方: n == 6, k == 2, 我们有这样一个数组[1, 2, 3, 4, 5, 6]
现在将数组重新排序,排序后要满足a[i + 1] > a[i](0<= i < n - 1)的次数等于k.
我们可以将数组后面k + 1个数放在前面,即[4, 5, 6, 1, 2, 3]
多举几个例子就可以发现上述规律.
代码
#include<bits/stdc++.h>
#define int long long #define endl '\n'
voidsolve(){ int n, k; std::cin >> n >> k; std::vector<int> a(n, 0ll); std::iota(a.begin(), a.end(), 1ll); for (int i = n - k - 1; i < n; i++) std::cout << a[i] << " "; for (int i = n - k - 2; i >= 0; i--) std::cout << a[i] << " "; std::cout << endl; }
signedmain(){ std::ios::sync_with_stdio(false); std::cin.tie(nullptr), std::cout.tie(nullptr); int Lazy_boy_ = 1; std::cin >> Lazy_boy_; while (Lazy_boy_--) solve(); return0; }
#define int long long #define endl '\n' [[maybe_unused]]typedef std::pair<int, int> pii;
voidsolve(){ int n, k; std::cin >> n >> k; std::vector<int> a(n + 1, 0ll), b(n + 1, 0ll); for (int i = 0; i < n; i++) std::cin >> a[i]; for (int i = 0; i < n; i++) std::cin >> b[i]; int s = 0, ma = 0, ans = 0; for (int i = 0; i < std::min(n, k); i++) { s += a[i]; ma = std::max(ma, b[i]); ans = std::max(ans, s + (k - i - 1) * ma); } std::cout << ans << endl; }
signedmain(){ std::ios::sync_with_stdio(false); std::cin.tie(nullptr), std::cout.tie(nullptr); int Lazy_boy_ = 1; std::cin >> Lazy_boy_; while (Lazy_boy_--) solve(); return0; }