Codeforces Beta Round #96 (Div. 1) D. Constants in the language of Shakespeare 贪心
D. Constants in the language of Shakespeare
Time Limit: 1 Sec
Memory Limit: 256 MB
题目连接
http://codeforces.com/contest/132/problem/DDescription
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=999999999; inline ll read() { ll x=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} return x*f; } //************************************************************************************* string s; int flag[maxn]; int main() { cin>>s; int n = s.size(); for(int i=0;i<n;i++) if(s[i]=='1')flag[n-1-i]=1; for(int i=0;i<n;i++) { if(flag[i]==0) continue; int j = i; while(flag[j])j++; if(j-i>=2) { flag[i]=-1; for(int k=i+1;k<=j;k++) flag[k]=0; flag[j]=1; } i=j-1; } int tot=0; for(int i=0;i<=n;i++) if(flag[i]==1||flag[i]==-1) tot++; printf("%d\n",tot); for(int i=0;i<=n;i++) { if(flag[i]==0) continue; if(flag[i]==1) printf("+2^%d\n",i); else printf("-2^%d\n",i); } }