D. Constants in the language of Shakespeare
Time Limit: 1 Sec
Memory Limit: 256 MB
题目连接
http://codeforces.com/contest/132/problem/D
Description
Shakespeare is a widely known esoteric programming language in which programs look like plays by Shakespeare, and numbers are given by combinations of ornate epithets. In this problem we will have a closer look at the way the numbers are described in Shakespeare.
Each constant in Shakespeare is created from non-negative powers of 2 using arithmetic operations. For simplicity we'll allow only addition and subtraction and will look for a representation of the given number which requires a minimal number of operations.
You are given an integer n. You have to represent it as n = a1 + a2 + ... + am, where each of ai is a non-negative power of 2, possibly multiplied by -1. Find a representation which minimizes the value of m.
Input
Output
Output the required minimal m. After it output m lines. Each line has to be formatted as "+2^x" or "-2^x", where x is the power coefficient of the corresponding term. The order of the lines doesn't matter.
Sample Input
1111
Sample Output
3
HINT
题意
给你一个2进制的数,然后要求你由+2^x和-2^x来构成这个数
使得需求的数最少
题解:
感觉好像是DP的样子,但是我DP灰常鶸,那就贪心咯
对于每一段连续的1,我们可以一个一个的点,也可以点开头然后灭掉结尾,很显然,当长度大于等于2的时候,第二种策略更加优秀
但是这儿有一个坑点,11101111,这个数据,答案是3
所以我们还要合并一次就行了~
代码:
//qscqesze
#include <cstdio>
#include <cmath>
#include <cstring>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <set>
#include <bitset>
#include <vector>
#include <sstream>
#include <queue>
#include <typeinfo>
#include <fstream>
#include <map>
#include <stack>
typedef long long ll;
using namespace std;
//freopen("D.in","r",stdin);
//freopen("D.out","w",stdout);
#define sspeed ios_base::sync_with_stdio(0);cin.tie(0)
#define maxn 1100000
#define mod 1001
#define eps 1e-9
#define pi 3.1415926
int Num;
//const int inf=0x7fffffff;
const ll inf=;
inline ll read()
{
ll x=,f=;char ch=getchar();
while(ch<''||ch>''){if(ch=='-')f=-;ch=getchar();}
while(ch>=''&&ch<=''){x=x*+ch-'';ch=getchar();}
return x*f;
}
//************************************************************************************* string s;
int flag[maxn];
int main()
{
cin>>s;
int n = s.size();
for(int i=;i<n;i++)
if(s[i]=='')flag[n--i]=;
for(int i=;i<n;i++)
{
if(flag[i]==)
continue;
int j = i;
while(flag[j])j++;
if(j-i>=)
{
flag[i]=-;
for(int k=i+;k<=j;k++)
flag[k]=;
flag[j]=;
}
i=j-;
}
int tot=;
for(int i=;i<=n;i++)
if(flag[i]==||flag[i]==-)
tot++;
printf("%d\n",tot);
for(int i=;i<=n;i++)
{
if(flag[i]==)
continue;
if(flag[i]==)
printf("+2^%d\n",i);
else
printf("-2^%d\n",i);
}
}