👨🏫 Shortest path
输入
4
7
114514
1919810
2147483648
输出
3
19
20
31
🍑 思路:用操作3 凑出 操作1 操作2 的前提条件,暴搜+记忆化搜索
import java.io.*;
import java.util.*;
public class Main
{
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
static HashMap<Long, Integer> map = new HashMap<>();
public static void main(String[] args) throws IOException
{
int T = Integer.parseInt(in.readLine());
while (T-- > 0)
{
long n = Long.parseLong(in.readLine());
map.clear();
int ans = cal(n);
out.write(ans + "\n");
}
out.flush();
}
public static int cal(long n)
{
if (n <= 1)
return (int) (1 - n);
if (map.containsKey(n))
return map.get(n);
int t1 = (int) (n % 2 + 1 + cal(n / 2));
int t2 = (int) (n % 3 + 1 + cal(n / 3));
int ans = Math.min(t1, t2);
map.put(n, ans);
return ans;
}
}
👨🏫 参考