cf-279E - Beautiful Decomposition-贪心

对于一串二进制。

若当前的值的情况是010,那么直接+1;

若当前值的情况是01...1(1的个数大于等于2)0,那么相当于最后一位变为1,然后减去第一个1;

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
using namespace std;
#define maxn 2000010
int maps[501][501];
int xx[5]={1,0,-1,0};
int yy[5]={0,-1,0,1};
int sum[maxn];
int num[maxn];
void init()
{
}
char str[maxn];
int main()
{
    int n,i,t;
    while(~scanf("%s",str))
    {
        int len=strlen(str);
        for(i=len;i>=1;i--)
        {
            num[i]=str[i-1]-'0';
        }
        int leap=0;
        int ms;
        ms=0;
        num[0]=0;
        for(i=len;i>=0;i--)
        {
            if(num[i]==0)
            {
                if(leap!=0)
                {
                    if(i==0)
                    {
                        ms++;
                        continue;
                    }
                    num[i]=1;
                    leap=0;
                    i++;
                }
            }
            else
            {
                if(leap==0)
                {
                    if(num[i-1]==1)
                    {
                        leap=1;
                        ms++;
                    }
                    else
                    {
                        ms++;
                        leap=0;
                    }
                }
            }
        }
        if(num[0]==1)ms++;
        cout<<ms<<endl;
    }
    return 0;
}


你可能感兴趣的:(cf-279E - Beautiful Decomposition-贪心)