It is obvious that
+ 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.+ 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.++ If F > 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?...?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;
}