codeforces 538B-Quasi Binary
time limit: per test2 seconds
memory limit: per test256 megabytes
input:standard input
output:standard output
A number is called quasibinary if its decimal representation contains only digits 0 or 1. For example, numbers 0, 1, 101, 110011 — are quasibinary and numbers 2, 12, 900 are not.
You are given a positive integer n. Represent it as a sum of minimum number of quasibinary numbers.
Input
The first line contains a single integer n (1 ≤ n ≤ 106).
Output
In the first line print a single integer k — the minimum number of numbers in the representation of number n as a sum of quasibinary numbers.
In the second line print k numbers — the elements of the sum. All these numbers should be quasibinary according to the definition above, their sum should equal n. Do not have to print the leading zeroes in the numbers. The order of numbers doesn’t matter. If there are multiple possible representations, you are allowed to print any of them.
Sample test(s)
input
9
output
9
1 1 1 1 1 1 1 1 1
input
32
output
3
10 11 11
这道题从数据上看不可能暴力破解,用贪心也能找到反例,动规也要看想不想的到,反正我是没想到什么比较好的动规方法,仔细一想,原来直接模拟就行了。下面我说下模拟的思路:
就拿32来说,把32每一位分开来看,则3=1+1+1, 2=1+1,接着把这些分解下来的1合成 所需要的数字就行了。
又比如53:
下面来说说为什么这样得到的是最优解。对于上面这种拆分方式,从地位开始到高位每一位单独考虑(其实也有点动规的意思),数字的个数一定不会超过9(因为没有哪一位会超过9)。如果以贪心来找最优解的话,每次找的是离目标最近的那个数,如果没有涉及到进位的加法,那么贪心和模拟得到的答案是一样的;但是一旦涉及到进位,因为需要的数组成不是0,就是1,需要进位就代表拆出来的数一定超过9个,而模拟出来的个数是不会超过9个的,所以能够说明这种方式的模拟得到的是最优解。
下面附上代码:
#include<iostream>
using namespace std;
int main(){
int n, a[15]={0}, t=1;
cin >> n;
while( n ){
int get = n%10;
for( int i=9 ; i>9-get ; i-- ) a[i] += t;
t *= 10;
n /= 10;
}
int tot = 0;
for( int i=0 ; i<10 ; i++ ) if( a[i] ) tot++;
cout << tot << endl;
for( int i=0 ; i<9 ; i++ ) if( a[i] ) cout << a[i] << " ";
cout << a[9] << endl;
return 0;
}