UVA 1374 Power Calculus

题意:

  给出m,问对n最少进行几次操作。n初始为1,能得到m。操作1位将n平方。操作2为将n除以之前出现的n值中的任意一个。

分析:

  其实是关于指数的操作,即从1到m最少的步数。我们可以先确定最少步数m,然后进行迭代,迭代的过程也就是判断通过相加减所得到的数可以在m次操作中等于n,如果符合,m即为最小步数,如果不符合,m++,进行下一次迭代。迭代过程中要注意剪枝,即剩余的次数如果每次都是取最大值相加还是比n小的话,就直接跳出。

代码:

  

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;
const int N=3005;
int n,tmp,vis[N],arr[N],ans[N],rec[N];
bool dfs(int d,int s)
{
if(d==tmp&&s==n)
return true;
if(d>=tmp||s>1500)
return false;
if(s*arr[tmp-d]<n)
return false;
rec[d]=s;
vis[s]=1;
int i,j;
for(i=0;i<=d;i++)
{
int u=rec[i]+s;
if(vis[u]==0)
if(dfs(d+1,u))
return true;
u=abs(s-rec[i]);
if(vis[u]==0)
if(dfs(d+1,u))
return true;
}
vis[s]=0;
return false;
}
int main()
{
arr[0]=1;
int i,j;
for(i=1;i<=31;i++)
arr[i]=arr[i-1]*2;
while(scanf("%d",&n)&&n)
{
tmp=0;
memset(vis,0,sizeof(vis));
while(1)
{
if(dfs(0,1))
break;
tmp++;
}
printf("%d ",tmp);
}
}
原文地址:https://www.cnblogs.com/137033036-wjl/p/4869552.html