Solution
It is obvious that
- If A A A has odd decimal-count, answer is 4...47...7 4...4 7...7 4...47...7
- Otherwise A A A (even decimal-count) if greater then 7...74...4 7...7 4...4 7...74...4, answer is also 4...47...7 4...4 7...7 4...47...7
- Otherwise the answer has the same decimal-count with
a
a
a.
+
A greedy-approach is wrong that iterate from the highest decimal if A [ i ] ≤ 4 A[i] \leq 4 A[i]≤4 then choose 4 4 4.
A example is 4478 4478 4478, you will get the answer 4477 4477 4477 using this algorithm.
+
The correct approach resembles the greedy with a additional check. For example, now you have the answer a b ? . . . ? ab?...? ab?...? ( ? ? ? denotes un-determined) and have F : 4 s , S : 7 s F: 4s, S: 7s F:4s,S:7s unused ( F + S F + S F+S equals the count of ? ? ?), let A n s w e r Answer Answer be a b ab ab.
++
IfF > 0
, let T = 7...74...4 T = 7...7 4...4 T=7...74...4 where contains S : 7 s S: 7s S:7s and ( F − 1 ) : 4 s (F-1): 4s (F−1):4s, if a b 4 T > A ab 4 T > A ab4T>A, then let A n s w e r = a b 4 ? . . . ? Answer = ab4 ?...? Answer=ab4?...?
++
Otherwise, A n s w e r = a b 7 ? . . . ? Answer = ab7 ?...? Answer=ab7?...?
Code
void __Solve( int _test_id){
( void)_test_id;
//--
long long a;
cin >> a;
vector< int> bits;
for( auto i = a; i > 0; i /= 10){
bits.push_back( i % 10);
}
reverse( bits.begin(), bits.end());
long long ans = -1;
if( bits.size() & 1){
ans = Form( bits.size() / 2 + 1, false);
}
else{
if( a > Form( bits.size() / 2, true)){
ans = Form( bits.size() / 2 + 1, false);
}
else{
int f = bits.size() / 2, s = bits.size() / 2;
ans = 0;
for( auto i : bits){
ans *= 10;
bool choose_four = false;
if( f > 0){
long long suf = 0, power = 1;
{
for(int ii = 1; ii < (s + f); ++ii){
power *= 10;
}
for( int ii = 0; ii < s; ++ii){
suf *= 10;
suf += 7;
}
for( int ii = 0; ii < f - 1; ++ii){
suf *= 10;
suf += 4;
}
}
if( (ans + 4) * power + suf >= a){
choose_four = true;
}
}
if( choose_four){
assert( f > 0);
-- f;
ans += 4;
}
else{
assert( s > 0);
-- s;
ans += 7;
}
}
}
}
assert( ans >= a);
cout << ans;
}