power of two--tiger--hihocoder

时间限制: 10000ms
单点时限: 1000ms
内存限制: 256MB

描述

Given a positive integer N, it is possible to represent N as the sum of several positive or negative powers of 2 (± 2k for some k). For example 7 can be represented as 22 + 21 + 20 and 23 + (-20).

Your task is to find the representation which contains the minimum powers of 2.

输入

One positive integer N.  

For 80% of the data: 1 <= N <= 100000  

For 100% of the data: 1 <= N <= 2000000000

输出

The minimum number of powers of 2.

样例输入

7

样例输出

2

自己写的过了50%的数据

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int64_t m;
    cin>>m;
    stack<int> mystack;
    while( m )
    {
        mystack.push(m%2);
        m>>=1;
    }
    int ans = 0;
    while( mystack.size() )
    {
        if( mystack.size() && mystack.top() )
        {
            ans++;
            mystack.pop();
            if( mystack.size()&&mystack.top() )
            {
                while( mystack.size() && mystack.top() )
                    mystack.pop();
                ans++;
            }
        }
        else
        {
            while( mystack.size()&&mystack.top() != 1 )
            {
                mystack.pop();
            }
        }
    }
    cout<<ans<<endl;
}

下面是参考了别人的代码,感觉自己和别人的差距还有很大
#include <bits/stdc++.h>

using namespace std;

map<unsigned int, int> dp;
unsigned int p[40];

void Init()
{
    p[0] = 1;
    dp[p[0]] = 1;
    for( int i=1; i<32 ; i++ )
    {
        p[i] = p[i-1]<<1;
        dp[p[i]] = 1;
    }
}
int dfs(unsigned int k )
{
    if( dp.count(k)) //map里面有k的话直接返回,没有的话递归求解;
        return dp[k];
    int L = lower_bound(p, p+32, k) - p - 1;
    int R = L + 1;
    return dp[k] = min(dfs(k-p[L]), dfs(p[R]-k)) + 1; //递归求解
}
int main()
{
    //freopen("in.txt", "r", stdin);
    Init();
    unsigned int N;
    cin>>N;
    cout<<dfs(N)<<endl;
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值