牛客题解 | 扭蛋机
题目
解题思路
这是一个贪心算法问题。关键点如下:
- 扭蛋机2号:投入 \(x\) 个扭蛋,可以得到 \(2x+1\) 个
- 扭蛋机3号:投入 \(x\) 个扭蛋,可以得到 \(2x+2\) 个
- 需要通过两人轮流使用扭蛋机,最终得到 \(N\) 个扭蛋
解题思路:
- 从目标数N开始反向推导
- 每次判断 \(N\) 的奇偶性:
- 如果 \(N\) 是偶数,使用3号机器,因为 \((n-2)/2\) 是整数
- 如果 \(N\) 是奇数,使用2号机器,因为 \((n-1)/2\) 是整数
- 每次操作后,更新 \(N\) 为投入的扭蛋数量
- 重复直到 \(N=0\),记录使用的机器顺序
代码
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
int n;
cin >> n;
string result;
while (n > 0) {
if (n % 2 == 0) {
n = (n - 2) / 2;
result += '3';
} else {
n = (n - 1) / 2;
result += '2';
}
}
reverse(result.begin(), result.end());
cout << result << endl;
return 0;
}
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
StringBuffer str = new StringBuffer();
while (n > 0) {
if (n % 2 == 0) {
n = (n - 2) / 2;
str.append("3");
} else {
n = (n - 1) / 2;
str.append("2");
}
}
str.reverse();
System.out.println(str);
}
}
n = int(input())
result = []
while n > 0:
if n % 2 == 0:
n = (n - 2) // 2
result.append('3')
else:
n = (n - 1) // 2
result.append('2')
print(''.join(result[::-1]))
算法及复杂度
- 算法:贪心
- 时间复杂度:\(\mathcal{O}(\log n)\) - 每次操作将 \(n\) 减半
- 空间复杂度:\(\mathcal{O}(\log n)\) - 需要存储结果字符串

浙公网安备 33010602011771号