Artifact Content
Not logged in

Artifact 7d7d14d6f38066ca64630a0e05c43865f342de7e


#include <iostream>
#include <sstream>
#include <iomanip>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <algorithm>
#include <numeric>
#include <iterator>
#include <functional>
#include <complex>
#include <queue>
#include <stack>
#include <cmath>
#include <cassert>
#include <cstring>
#ifdef __GNUC__
#include <ext/hash_map>
#define unordered_map __gnu_cxx::hash_map
#else
#include <unordered_map>
#endif
using namespace std;
typedef long long LL;
typedef complex<double> CMP;

class SumOfLuckiness { public:
	long long theSum(int A, int B)
	{
		return theSum(B) - theSum(A-1);
	}

	LL theSum(LL X)
	{
		string S; {stringstream ss; ss<<X; ss>>S;}
		memo.clear();
		return rec(S, 0, 0);
	}

	LL rec(const string& S, int i, int dif)
	{
		if( i == S.size() )
			return abs(dif);

		LL total = rec(S, i+1, dif+(S[i]=='4')-(S[i]=='7'));
		for(char c='0'; c<S[i]; ++c)
			total += count_all(S.size() - (i+1), dif+(c=='4')-(c=='7'));
		return total;
	}

	map<pair<int,int>, LL> memo;
	LL count_all(int n, int dif)
	{
		if( n == 0 )
			return abs(dif);

		const pair<int,int> key(n, dif);
		if( memo.count(key) )
			return memo[key];

		LL total = 0;
		for(char c='0'; c<='9'; ++c)
			total += count_all(n-1, dif+(c=='4')-(c=='7'));
		return memo[key] = total;
	}
};

// BEGIN CUT HERE
#include <ctime>
double start_time; string timer()
 { ostringstream os; os << " (" << int((clock()-start_time)/CLOCKS_PER_SEC*1000) << " msec)"; return os.str(); }
template<typename T> ostream& operator<<(ostream& os, const vector<T>& v)
 { os << "{ ";
   for(typename vector<T>::const_iterator it=v.begin(); it!=v.end(); ++it)
   os << '\"' << *it << '\"' << (it+1==v.end() ? "" : ", "); os << " }"; return os; }
void verify_case(const long long& Expected, const long long& Received) {
 bool ok = (Expected == Received);
 if(ok) cerr << "PASSED" << timer() << endl;  else { cerr << "FAILED" << timer() << endl;
 cerr << "\to: \"" << Expected << '\"' << endl << "\tx: \"" << Received << '\"' << endl; } }
#define CASE(N) {cerr << "Test Case #" << N << "..." << flush; start_time=clock();
#define END	 verify_case(_, SumOfLuckiness().theSum(A, B));}
int main(){

CASE(0)
	int A = 1; 
	int B = 10; 
	long long _ = 2LL; 
END
CASE(1)
	int A = 40; 
	int B = 47; 
	long long _ = 8LL; 
END
CASE(2)
	int A = 58; 
	int B = 526; 
	long long _ = 231LL; 
END
CASE(3)
	int A = 4444; 
	int B = 7777; 
	long long _ = 2338LL; 
END
CASE(4)
	int A = 585858585; 
	int B = 858585858; 
	long long _ = 287481025LL; 
END
CASE(5)
	int A = 1; 
	int B = 1; 
	long long _ = 0LL; 
END
CASE(6)
	int A = 1; 
	int B = 2000000000; 
	long long _ = -1LL; 
END

}
// END CUT HERE