牛客春招刷题训练营-2025.5.12题解
活动地址: 牛客春招刷题训练营 - 编程打卡活动
简单题 小红的魔法药剂
记 为获得第
种红色、蓝色版本魔法药剂的花费。
红色药剂只能直接购买:。
蓝色药剂需要合成:。
答案 。
时间复杂度 。
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> red(n + 1), blue(n + 1);
for (int i = 1; i <= n; i++)cin >> red[i];
for (int i = 1; i <= n; i++) {
int b, c;
cin >> b >> c;
blue[i] = red[b] + red[c];
}
long long ans = 0;
for (int i = 1; i <= n; i++)
ans += min(red[i], blue[i]);
cout << ans << '\n';
return 0;
}
中等题 游游的字母翻倍
不算大,且最终字符串不超过
,所以能直接模拟。
每次模拟时开辅助字符串 ,遍历
时如果
则给
添加
个
,否则添加
个
,每一轮结束后将
赋值给
。
时间复杂度 ,
可看作
。
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, q;
cin >> n >> q;
string s1, s2;
cin >> s1;
while (q--) {
int l, r;
cin >> l >> r;
l--;
r--;
s2 = "";
for (int i = 0; i < s1.length(); i++) {
if (l <= i && i <= r) {
s2 += s1[i];
s2 += s1[i];
} else s2 += s1[i];
}
s1 = s2;
}
cout << s1;
return 0;
}
困难题 游游的数值距离
考虑到 不会很大,最大值只能取到
,因为
,所以只需暴力枚举
,算出当前的
下使原式最小的
。
当 时,发现原式恒等于
。
当 时,我们将原式变换一下,即最小化
。
记 。
是随
单调递增的,而我们知道一个使得
最大的
,等于
。
所以使得 最小的
的取值只能是
或
。
如果计算出的 或
不为
,则将
或
代入原式,如果计算值比当前存储的原式最小值小,则更新
的答案且更新原式最小值。
时间复杂度 ,其实可以看作一个很大的常数。
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
ll frac(int n) {
ll res = 1;
for (int i = 2; i <= n; i++)res *= i;
return res;
}
ll calc(int x, int y, int n) {
return abs(frac(x) * y - y - n);
}
int main() {
int n;
cin >> n;
int ansx = 1, ansy = 1;
ll minabs = n;
for (int x = 3; x <= 13; x++) {
int y = n / (frac(x) - 1);
if (y != 2) {
ll nowabs = calc(x, y, n);
if (nowabs < minabs) {
ansx = x;
ansy = y;
minabs = nowabs;
}
}
if (y + 1 != 2) {
ll nowabs = calc(x, y + 1, n);
if (nowabs < minabs) {
ansx = x;
ansy = y + 1;
minabs = nowabs;
}
}
}
cout << ansx << ' ' << ansy << '\n';
return 0;
}