标签:
题目链接:点击打开链接
题意:
输入一个n(n<=1000)
问:有一个x,最少需要几次乘除可以算出x^n。
思路:
记忆化搜索
a[i] = j 表示i次幂需要j步得到
import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Scanner; import java.util.TreeSet; import java.util.Queue; public class Main { static int N = 1000050; int[] a = new int[N]; boolean dfs(int n, int num, int step){//用step步是否能得到n次,当前步数为num步 if(num > step)return false; if(a[num] == n)return true; if((a[num] << (step-num)) < n)//一直平方也达不到n return false; for(int i = 0; i <= num; i++){ a[num+1] = a[num]+a[i]; if(a[num+1] <= 10000 && dfs(n,num+1,step)) return true; a[num+1] = a[num] - a[i]; if(a[num+1] > 0 && dfs(n,num+1, step)) return true; } return false; } void work() { while(true){ int n = cin.nextInt(); if(n == 0)break; int i; for(i = 0; ; i++){ a[0] = 1; if(dfs(n, 0, i))break; } out.println(i); } } Main() { cin = new Scanner(System.in); out = new PrintWriter(System.out); } public static void main(String[] args) { Main e = new Main(); e.work(); out.close(); } public Scanner cin; public static PrintWriter out; }
UVALive 3621 Power Calculus n次幂最少需要几次乘除得到 搜索
标签:
原文地址:http://blog.csdn.net/qq574857122/article/details/43027339