maze_python/codeforces_c3_v2.py
2025-06-30 21:05:34 +08:00

111 lines
3.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
import sys
def solve():
n = int(input())
# 基于理论分析的最优策略:
# 对任意目标n我们可以证明存在一个通用的构造方法
# 关键观察:
# 1. digit操作将任何数转换为其数字和最终会到1-9范围
# 2. 从任何1-9的数我们都可以用很少操作构造任意目标
# 最优构造策略:
if n == 1:
# 对于目标1digit -> 然后想办法变为1
print("digit")
sys.stdout.flush()
response = int(input())
# 现在尝试各种方法变为1
# 方法1: 如果当前是偶数,除以自身
for d in [2, 3, 4, 5, 6, 7, 8, 9]:
print(f"div {d}")
sys.stdout.flush()
response = int(input())
if response == 1:
# 除法成功现在可能是1或其他数
# 继续尝试到达1
break
# 方法2: 用加法调整
for adj in range(-8, 9):
if adj != 0:
print(f"add {adj}")
sys.stdout.flush()
response = int(input())
if response == 1:
break
elif 2 <= n <= 9:
# 对于2-9digit -> 调整到目标
print("digit")
sys.stdout.flush()
response = int(input())
# 枚举所有可能的当前值尝试调整到n
for current in range(1, 10):
diff = n - current
print(f"add {diff}")
sys.stdout.flush()
response = int(input())
if response == 1:
break
else:
# 对于n > 9使用构造策略
# 策略digit -> 构造一个因子 -> 乘法得到n
print("digit")
sys.stdout.flush()
response = int(input())
# 寻找n的最小因子除了1
smallest_factor = n
for f in range(2, min(10, n + 1)):
if n % f == 0:
smallest_factor = f
break
if smallest_factor < n:
# 找到了因子,使用分解策略
quotient = n // smallest_factor
# 尝试构造smallest_factor
for current in range(1, 10):
diff = smallest_factor - current
print(f"add {diff}")
sys.stdout.flush()
response = int(input())
if response == 1:
# 成功构造factor现在乘以quotient
print(f"mul {quotient}")
sys.stdout.flush()
response = int(input())
break
else:
# n是质数或没有小因子使用直接加法
for current in range(1, 10):
diff = n - current
if diff > 0 and diff <= 10**18:
print(f"add {diff}")
sys.stdout.flush()
response = int(input())
if response == 1:
break
# 输出答案
print("!")
sys.stdout.flush()
final_response = int(input())
def main():
t = int(input())
for _ in range(t):
solve()
if __name__ == "__main__":
main()