您可以找到问题陈述here。 我的解决方案可以找到here。我得到了测试案例的正确答案,但法官指出所有答案都是错误的。我的代码出了什么问题?
#include <iostream>
#include <vector>
#include <map>
#include <math.h>
using namespace std;
map<long long,long long> arr;
void preProcess();
long long powerOfThree(long long num);
long long powerOfTwo(long long num);
long long theta(long long num);
int main()
{
preProcess();
long long t,k;
cin>>t;
while(t--)
{
cin>>k;
cout<<theta(k)<<endl;
}
}
void preProcess()
{
arr.insert(pair<long long,long long>(0,0));//arr[0]=0;
arr.insert(pair<long long,long long>(1,0));//arr[1]=0;
arr.insert(pair<long long,long long>(2,1));//arr[2]=1;
arr.insert(pair<long long,long long>(3,1));//arr[3]=1;
//arr.insert(pair<long long,long long>(4,2));//arr[4]=2;
//arr.insert(pair<long long,long long>(5,3));//arr[5]=3;
}
long long powerOfTwo(long long num)
{
long long ret=0;
while(num%2==0)
{
ret++;
num = num/2;
}
return ret;
}
long long theta(long long num)
{
long long ret;
map<long long,long long>::iterator it = arr.find(num);
if(it != arr.end())
{
return arr[num];
}
else
{
if(num%2==0)
{
long long a = powerOfTwo(num);
long long q = (num/(long long)pow(2,a));
ret = a + theta(q);
}
else if(num%3==0)
{
long long a = powerOfThree(num);
long long q = (num/(long long)pow(3,a));
ret = a + theta(q);
}
else
{
ret = 1 + theta(num-1);
}
}
arr.insert(pair<long long,long long>(num,ret));//arr[num]=ret;
return ret;
}
long long powerOfThree(long long num)
{
long long ret=0;
while(num%3==0)
{
ret++;
num = num/3;
}
return ret;
}
我的方法是首先计算数字中2和3的所有幂,然后将结果减少1.再次重复该过程直到它为1.
答案 0 :(得分:1)
你的方法会失败,例如(2 ^ 8 + 1)* 3 ^ 2。实际上会有很多这样的数字。
我会在Python中给出一个解决方案(bcoz这就是我所熟悉的):
step = [0,0,1,1]
def find(a):
global step
t = len(step)
for n in range(t,a+1):
if ((n%3 == 0) and (n%2 == 0)):
step.append( 1 + min(step[n-1],step[n/2],step[n/3]))
elif (n%2==0):
step.append( 1 + min(step[n-1],step[n/2]))
elif (n%3 == 0) :
step.append( 1 + min(step[n-1],step[n/3]))
else :
step.append( 1 + step[n-1])
return step[a]
n = int(raw_input())
arr = []
for a in range(0,n):
arr.append(raw_input())
for st in arr:
n = int(st)
print find(n)