ones
时间限制:1000 ms | 内存限制:65535 KB
难度:3
描述
Given a positive integer N (0<=N<=10000), you are to find an expression equals to N using only 1,+,*,(,). 1 should not appear continuously, i.e. 11+1 is not allowed.
输入
There are multiple test cases. Each case contains only one line containing a integer N
输出
For each case, output the minimal number of 1s you need to get N.
样例输入
2
10
样例输出
2
7
题意就是:给定一个数n,通过加和乘运算组合得到n,计算最少需要多少个1。
思路:如果是素数,那么它只能通过前面的一个数+1得到,如果不是,则可以分解成两个因子的乘积,且此时也需要对是素数的dp[i-1]+1进行比较,则状态转移方程为dp[i]=min(dp[i],dp[j],dp[i/j])。
#include<stdio.h>
#include<algorithm>
#include<stdlib.h>
#include<iostream>
#include<string.h>
#include<vector>
#include<queue>
#include<math.h>
using namespace std;
int dp[10005];
void fun()
{
dp[0]=0;
dp[1]=1;
dp[2]=2;
for(int i=3;i<=10000;i++)
{
dp[i]=dp[i-1]+1;
for(int j=1;j<=i;j++)
{
if(i%j==0)
dp[i]=min(dp[i],dp[j]+dp[i/j]);
}
}
}
int main()
{
fun();
int n;
while(~scanf("%d",&n))
{
printf("%d\n",dp[n]);
}
return 0;
}