Nyoj 708 Ones

1431 단어 dp
#include <iostream>
#include <cstring>
#include <cstdio>

using namespace std;

const int MAXN = 10010;

int dp[MAXN];

int MIN(int a, int b)
{
    return a < b ? a : b;
}

void Pre_Solve()
{
    dp[1] = 1;
    dp[2] = 2;
    for(int i = 3; i < MAXN; ++i)
    {
        dp[i] = i;
        for(int j = 1; j < i; ++j)
        {
            dp[i] = MIN(dp[i], dp[i-j] + dp[j]);
            if( j != 1 && !(i%j))
                dp[i] = MIN(dp[i], dp[i/j] + dp[j]);
        }
    }
}

int main()
{
    int n;
    memset(dp, 0, sizeof(dp));
    Pre_Solve();
    
    while(~scanf("%d", &n))
    {
        printf("%d
",dp[n]); } return 0; }

0ms 코드:
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdio>


using namespace std;

const int MAXN = 10010;
const int INF = 0xfffffff;

int dp[MAXN];

void Pre_Solve()
{
    fill(dp, dp+MAXN, INF);
    int i, j;
    dp[1] = 1;
    for(i = 2; i < MAXN; ++i)
    {
        dp[i] = min(dp[i], dp[i-1] + 1);
        for(j = 1; j <= i && i*j < MAXN; ++j)
            dp[i*j] = min(dp[i*j], dp[i] + dp[j]);
    }
}

int main()
{
    int n;
    Pre_Solve();
    while(~scanf("%d", &n))
    {
        printf("%d
", dp[n]); } return 0; }

좋은 웹페이지 즐겨찾기