1025.divisor-game
Statement
Metadata
- Link: 除数博弈
- Difficulty: Easy
- Tag:
脑筋急转弯
数学
动态规划
博弈
爱丽丝和鲍勃一起玩游戏,他们轮流行动。爱丽丝先手开局。
最初,黑板上有一个数字 n
。在每个玩家的回合,玩家需要执行以下操作:
- 选出任一
x
,满足0 < x < n
且n % x == 0
。 - 用
n - x
替换黑板上的数字n
。
如果玩家无法执行这些操作,就会输掉游戏。
只有在爱丽丝在游戏中取得胜利时才返回 true
。假设两个玩家都以最佳状态参与游戏。
示例 1:
输入:n = 2
输出:true
解释:爱丽丝选择 1,鲍勃无法进行操作。
示例 2:
输入:n = 3
输出:false
解释:爱丽丝选择 1,鲍勃也选择 1,然后爱丽丝无法进行操作。
提示:
1 <= n <= 1000
Metadata
- Link: Divisor Game
- Difficulty: Easy
- Tag:
Brainteaser
Math
Dynamic Programming
Game Theory
Alice and Bob take turns playing a game, with Alice starting first.
Initially, there is a number n
on the chalkboard. On each player's turn, that player makes a move consisting of:
- Choosing any
x
with0 < x < n
andn % x == 0
. - Replacing the number
n
on the chalkboard withn - x
.
Also, if a player cannot make a move, they lose the game.
Return true
if and only if Alice wins the game, assuming both players play optimally.
Example 1:
Input: n = 2
Output: true
Explanation: Alice chooses 1, and Bob has no more moves.
Example 2:
Input: n = 3
Output: false
Explanation: Alice chooses 1, Bob chooses 1, and Alice has no more moves.
Constraints:
1 <= n <= 1000
Solution
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define endl "\n"
#define fi first
#define se second
#define all(x) begin(x), end(x)
#define rall rbegin(a), rend(a)
#define bitcnt(x) (__builtin_popcountll(x))
#define complete_unique(a) a.erase(unique(begin(a), end(a)), end(a))
#define mst(x, a) memset(x, a, sizeof(x))
#define MP make_pair
using ll = long long;
using ull = unsigned long long;
using db = double;
using ld = long double;
using VLL = std::vector<ll>;
using VI = std::vector<int>;
using PII = std::pair<int, int>;
using PLL = std::pair<ll, ll>;
using namespace __gnu_pbds;
using namespace std;
template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
const ll mod = 1e9 + 7;
template <typename T, typename S>
inline bool chmax(T &a, const S &b) {
return a < b ? a = b, 1 : 0;
}
template <typename T, typename S>
inline bool chmin(T &a, const S &b) {
return a > b ? a = b, 1 : 0;
}
#ifdef LOCAL
#include <debug.hpp>
#else
#define dbg(...)
#endif
// head
class Solution {
public:
bool divisorGame(int n) {
auto f = vector<int>(n + 1, false);
for (int i = 2; i <= n; i++) {
for (int j = 1; j < i; j++) {
if (i % j == 0 && f[i - j] == false) {
f[i] = true;
break;
}
}
}
return f[n];
}
};
#ifdef LOCAL
int main() {
return 0;
}
#endif
最后更新: October 11, 2023