zoukankan      html  css  js  c++  java
  • poj3134 Power Calculus

    1. 题意:给定一个n,从x出发只用乘除法,求出算出x^n的最小步数。即从1出发只用加减法算出n的最小步数。
    2. 分析:求最小步数想到用bfs,但bfs不能记录已经到达过的状态结果,又想到用dfs,但盲目的dfs,状态太多,时间开销太大,所以选择使用IDDFS。

    code:

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <cmath>
    #include <algorithm>
    #include <cstdlib>
    using namespace std;
    int n,dp,a[1005];
    
     bool iddfs(int t,int Max)
    {
    	if (a[t]==n) return true;
    	if (t>=dp) return false;//超过迭代深度
        Max=max(Max,a[t]);
    	if (Max>n&&a[t]>n) return false;
    	if (Max*(1<<(dp-t))<n) return false;//无论怎么计算都无法得到n
    	for (int i=0; i<=t; i++)
    	{
    		a[t+1]=a[t]+a[i];
    		if (iddfs(t+1,Max)) return true;
    		if (a[t]>a[i]) a[t+1]=a[t]-a[i];
    		else a[t+1]=a[i]-a[t];
    		if (iddfs(t+1,Max)) return true;
    	} 
    	return false;
    }
    
     int main()
    {
    	while (scanf("%d",&n)&&n)
    	{
    		if (n==1) printf("0
    ");
    		else
    		{
    			a[0]=1; 
    			for (dp=1; 1; dp++)
    				if (iddfs(0,1)) 
    				{
    					printf("%d
    ",dp); break;
    				}
    		}
    	}
    	return 0;
    }
    
  • 相关阅读:
    代理模式第一篇
    命令模式第二篇
    windows service 定时
    postman之asp.net webapi
    qq第三方登录
    core2.1下的identity 汉化
    asp.net core2.0里的Nlog
    Unable to create an object of type 'ApplicationDbContext'.
    identity使用mysql
    二进制位运算解决状态值
  • 原文地址:https://www.cnblogs.com/lyxzhz/p/12185771.html
Copyright © 2011-2022 走看看