C. One-Based Arithmetic
题意:给一个数n,你可以用若干个各位全为1的十进制数和+、-这两个运算符凑成n。问最少需要多少个“1”。
思路:dfs。假设当前需要凑的数是x,要么用恰好比它大的“全1”减去它,要么减去恰好比它小的“全1”。不过这样做的解答树太大了,会超时,借用dp的思想,去保存解答树中接近树叶的部分,减少了重复运算,大大降低了运行时间。
这是很久之前的CF题了,当时未解决,现在翻出来做做,看看自己水平提高了没有。。。
#include <iostream>
#include <stdio.h>
#include <cmath>
#include <algorithm>
#include <iomanip>
#include <cstdlib>
#include <string>
#include <memory.h>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <ctype.h>
#include <sstream>
#define INF 1000000000
#define ll long long
#define min3(a,b,c) min(a,min(b,c))
#define max3(a,b,c) max(a,max(b,c))
#define MAXN 1010
using namespace std;
int dp[100000];
int dfs(ll x){
if(!x)return 0;
if(x==1)return 1;
if(x<100000&&dp[x])return dp[x];
//cout<<"x="<<x<<endl;
ll t=1;
int cnt=1;
while(t<x){
t*=10; t+=1; cnt++;
}
int re=INF;
if(t-x<x-t/10){
re=cnt+dfs(t-x);
}
if(t!=x)re=min(re,cnt-1+dfs(x-t/10));
if(x<100000)dp[x]=re;
return re;
}
int main(){
ll n;
while(cin>>n){
int ans=dfs(n);
cout<<ans<<endl;
}
return 0;
}