C. One-Based Arithmetic
time limit per test

0.5 seconds

memory limit per test

256 megabytes

input

standard input

output

standard output

Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.

Input

The first line of the input contains integer n (1 ≤ n < 1015).

Output

Print expected minimal number of digits 1.

Sample test(s)
Input
121
Output
6

http://codeforces.com/contest/440/problem/C

用一堆由1组成的数来加减得到某数,输入某数,求最少要用多少个1。

深搜!由于这题的性质,每次搜肯定能得到一个解,然后之后搜的时候用的1数大于这个解,就可以跳出,怒剪了一大波枝。(最优性剪枝)

就是从最高位开始,慢慢把位削成0。因为把第i位消除成0后,可以选择数保证这一位不会再变回1,所以就一位一位消下去就行。

深搜只有两种方向,例如第i位是x,第一种方向就是搞x个11111把它消了,另一种是搞一堆11111把它加上去,然后搞一个多一位的111111把它再消掉,这两种都有可能,而其他的方法都不如这2种。

所以哐哐哐就是搜啦!搜啊!

 #include<cstdio>
#include<cstring>
#include<iostream>
#include<cstdlib>
#include<cmath>
using namespace std; typedef long long ll; int ans,len;
ll one[]={,,,,,,,,,,
1111111111LL,11111111111LL,111111111111LL,1111111111111LL,
11111111111111LL,111111111111111LL,1111111111111111LL};
void dfs(ll x,int sum)
{
int a,b;
if(sum>=ans) return;
if(x==)
{
ans=sum;
return;
}
if(x<) x=-x;
ll y=x;
int t=;
while(y!=) t++,y/=;
ll reta=x,retb=one[t+]-x;
ll h=pow(,t-);
int sa=,sb=t+;
while(reta>=h) reta-=one[t],sa+=t;
while(retb>=h) retb-=one[t],sb+=t;
dfs(reta,sum+sa);
dfs(retb,sum+sb);
return;
} int main()
{
ll x;
while(scanf("%I64d",&x)!=EOF)
{
ans=1e9;
dfs(x,);
printf("%d\n",ans);
}
return ;
}

CF440C的更多相关文章

随机推荐

  1. [CareerCup] 11.2 Sort Anagrams Array 异位词数组排序

    11.2 Write a method to sort an array of strings so that all the anagrams are next to each other. 这道题 ...

  2. checkbox radio select绑定

    index11.html <html><head> <title>checkbox radio select绑定</title> <script ...

  3. Java并发编程-CopyOnWriteArrayList

    CopyOnWriteArrayList原理 首先每次写操作,都将数组copy一份,并赋值给arrays 读操作读不加锁 写操作加锁 ReentrantLock 因为每次写都要copy数组,这是一项繁 ...

  4. [c#基础]集合foreach的必要条件和自定义集合

    引言 最近翻看了之前的学习笔记,看到foreach,记得当时老师讲的时候,有点犯浑,不是很明白,这好比,上小学时,你不会乘法口诀,但是随着时间的增长,你不自觉的都会了,也悟出个小道理,有些东西,你当时 ...

  5. 5、面向对象以及winform的简单运用(方法重载、隐藏、重写与虚方法)

    方法的重载: 规定一个方法可以具有不同的实现,但方法的名称是相同的.如: //同样是Man这个方法 public int Man(int age,int name) { …… } //重载 publi ...

  6. JS事件学习笔记(思维导图)

    导图

  7. Objective-C 高性能的循环遍历 forin - NSEnumerator - 枚举 优化

    Cocoa编程的一个通常的任务是要去循环遍历一个对象的集合  (例如,一个 NSArray, NSSet 或者是 NSDictionary). 这个看似简单的问题有广泛数量的解决方案,它们中的许多不乏 ...

  8. 修改ssh的访问端口号

    [root@redis143 ~]# vim /etc/ssh/sshd_config 修改其中的:Port 10056 重启sshd服务 同时如果有防火墙规则的话,注意修改防火墙规则,或者关闭防火墙 ...

  9. js-定时任务setInterval,setTimeout,clearInterval,clearTimeout

    setInterval()循环执行相应的方法 <script type="text/javascript"> setInterval("myInterval( ...

  10. Hibernate-Criteria用法

    criteria 英[kraɪˈtɪərɪə] 美[kraɪˈtɪrɪə] Hibernate 设计了 CriteriaSpecification Hibernate 设计了 CriteriaSpec ...