码迷,mamicode.com
首页 > 其他好文 > 详细

UVA 1374 Power Calculus

时间:2017-10-14 21:15:55      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:pow   bool   for   输入   pac   get   题意   power   span   

https://vjudge.net/problem/UVA-1374

 

题意:

输入n,问最少需要几次乘除法可以从x得到x^n

 

每次从当前状态集和找两个数相加减

只需要用刚搜出的数 与之前的数即可

 

#include<cstdio>

using namespace std;

int n,maxd;

int ans[1001]={1};

bool dfs(int d)
{
    int pre=ans[d-1];
    if(d==maxd+1) return pre==n;
    if((pre<<maxd-d+1)<n) return false;
    for(int i=d-1;i>=0;i--)
    {
        ans[d]=pre+ans[i];
        if(ans[d]==n || dfs(d+1)) return true;
        ans[d]=pre-ans[i];
        if(ans[d]>0 && (ans[d]==n || dfs(d+1))) return true;
    }
    return false;
} 

int main()
{
    while(scanf("%d",&n)!=EOF)
    {
         if(!n) return 0;
         if(n==1)  { printf("0\n"); continue; }
         for(maxd=1;;maxd++) 
         {
             if(dfs(1)) break;
         }
         printf("%d\n",maxd);
        // for(int i=0;i<=maxd;i++) printf("%d ",ans[i]);
    }

}

 

UVA 1374 Power Calculus

标签:pow   bool   for   输入   pac   get   题意   power   span   

原文地址:http://www.cnblogs.com/TheRoadToTheGold/p/7668402.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!