#include<bits/stdc++.h>
using namespace std;
#define ll long
#define out(a) copy(a.begin(),a.end(),ostream_iterator<int>(cout," "))
const ll N = 88888888888888 ;
struct node {
int indx; ll sum;
bool mod;
bool f, p;
node( int indx, ll sum, bool mod, bool f, bool p) :
indx( indx) , sum( sum) , mod( mod) , f( f) , p( p) {
}
} ;
class LuckySum {
public :
long long construct( string note) {
if ( note.find_first_not_of ( "?" ) == string:: npos ) {
if ( note.size ( ) == 1 ) return 8 ;
ll x = 11 ;
int st = note.size ( ) - 2 ;
while ( st > 0 ) {
x* = 10 ;
x+ = 8 ;
-- st;
}
return x;
}
ll ans = 1e15 ;
ll val[ 16 ] ;
val[ 0 ] = 1 ;
for ( int i = 1 ; i <= 15 ; ++ i)
val[ i] = val[ i - 1 ] * 10 ;
queue< node> que;
que.push ( node( 0 , 0 , 0 , 0 , 0 ) ) ;
while ( que.size ( ) ) {
node tmp = que.front ( ) ;
que.pop ( ) ;
if ( tmp.sum > val[ note.size ( ) ] )
continue ;
if ( tmp.indx + tmp.mod == ( int ) note.size ( ) ) {
ll x = tmp.sum ;
int st = note.size ( ) ;
while ( x && st >= 0 ) {
-- st;
int y = x % 10 ;
x / = 10 ;
if ( note[ st] == '?' || ( note[ st] - '0' == y) )
continue ;
x = tmp.sum ;
tmp.sum = - 1 ;
break ;
}
if ( tmp.sum ! = - 1 )
ans = min( ans, tmp.sum ) ;
tmp.sum = x;
}
if ( tmp.indx == 0 ) {
que.push ( node( tmp.indx + 1 , 8 , 0 , 0 , 0 ) ) ;
que.push ( node( tmp.indx + 1 , 11 , 1 , 0 , 0 ) ) ;
que.push ( node( tmp.indx + 1 , 14 , 1 , 0 , 0 ) ) ;
continue ;
}
if ( ! tmp.f ) {
que.push (
node( tmp.indx + 1 , tmp.sum + 4 * val[ tmp.indx ] , 0 , 0 ,
1 ) ) ;
que.push (
node( tmp.indx + 1 , tmp.sum + 7 * val[ tmp.indx ] , 0 , 0 ,
1 ) ) ;
if ( ! tmp.p ) {
que.push (
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