时间限制:
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;
}