题解:CF585C Alice, Bob, Oranges and Apples

· · 题解

1 1 
1 2 1B
1 3 2B
1 4 3B
1 5 4B
1 6 5B
1 7 6B
1 8 7B
1 9 8B
1 10 9B
2 1 1A
2 3 1B1A
2 5 2B1A
2 7 3B1A
2 9 4B1A
3 1 2A
……

令 \mathrm{solve}(o,a) 为原有 o 个橘子,a 个苹果的方案。

则观察可得 \mathrm{solve}(1,n)=(n-1)B。

当 $a>o$ 时,$\mathrm{solve}(o,a)= ( \lfloor \frac b a \rfloor B)(\mathrm{solve}(o,a \bmod o)A)$。 否则答案为 $\mathrm{inv}(\mathrm{solve}(a, o))$,$\mathrm{inv}(s)$ 定义为将 $s$ 串中的 $A,B$ 互换。 观察可知其过程类似欧几里得算法,故时间复杂度为 $O(\log \max(o,a))$。 代码如下: ```cpp #include <bits/stdc++.h> using namespace std; using ll = long long; ll o, a; inline ll gcd(ll a, ll b) { if (!b) return a; return gcd(b, a % b); } inline string ct(string x) { int sz = x.size(); for (int i = 0; i < sz; i++) if (!isdigit(x[i])) x[i] = x[i] == 'A' ? 'B' : 'A'; return x; } inline string solve(ll x, ll y) { if (x == 1) return y > 1 ? to_string(y - 1) + "B" : ""; if (y == 1) return x > 1 ? to_string(x - 1) + "A" : ""; int op = 1; if (x > y) swap(x, y), op = -1; string t = to_string(y / x) + "B" + solve(x, y % x); return op == -1 ? ct(t) : t; } int main() { scanf("%lld%lld", &o, &a); if (gcd(o, a) != 1 || (o == 1 && a == 1)) return puts("Impossible"), 0; printf("%s\n", solve(o, a).c_str()); return 0; } ```