Tarango

Problem D

Aug 19th, 2015
323
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.89 KB | None | 0 0
  1. //============================================================================
  2. // Name        : ACM
  3. // Author      : Tarango Khan
  4. // Copyright   : Team Byteheads
  5. // Description : !!!Hello World!!!
  6. //============================================================================
  7.  
  8. #include <bits/stdc++.h>
  9. using namespace std;
  10. #define Size 150005
  11. #define Max 150005
  12.  
  13. string int2str(long long a) {
  14.     stringstream ss;
  15.     ss << a;
  16.     string str = ss.str();
  17.     return str;
  18. }
  19.  
  20. long long DP[18][2][165][1460];
  21. int N;
  22. string num;
  23. long long st,ed;
  24.  
  25. bool RelativelyPrime (long long a, long long b) {
  26.     if(a == 0 || b == 0) return false;
  27.     for (;;) {
  28.         if (!(a %= b)) return b == 1;
  29.         if (!(b %= a)) return a == 1;
  30.     }
  31.     return 0;
  32. }
  33.  
  34. long long call(int cur,int dgt_sum,int sqr_sum,bool f){
  35.     if(cur == N){
  36.         if(RelativelyPrime(dgt_sum,sqr_sum) == true) return 1;
  37.         return 0;
  38.     }
  39.     if(DP[cur][f][dgt_sum][sqr_sum] != -1)  return DP[cur][f][dgt_sum][sqr_sum];
  40.     long long res = 0;
  41.     int add1 = 0,add2 = 0;
  42.     if(f == true){
  43.         for(char ch = '0';ch<=num[cur];ch++){
  44.             int dgt = (int)(ch - '0');
  45.             add1 = dgt,add2 = dgt*dgt;
  46.             if(ch == num[cur]){
  47.                 res = res + call(cur+1,(dgt_sum+add1),(sqr_sum+add2),true);
  48.             }else{
  49.                 res = res + call(cur+1,(dgt_sum+add1),(sqr_sum+add2),false);
  50.             }
  51.         }
  52.     }else{
  53.         for(char ch = '0';ch<='9';ch++){
  54.             int dgt = (int)(ch - '0');
  55.             add1 = dgt,add2 = dgt*dgt;
  56.             res = res + call(cur+1,(dgt_sum+add1),(sqr_sum+add2),false);
  57.         }
  58.     }
  59.     return DP[cur][f][dgt_sum][sqr_sum] = res;
  60. }
  61.  
  62. int main() {
  63.     int nCase;
  64.     scanf("%d",&nCase);
  65.     for(int cs = 1;cs<=nCase;cs++){
  66.         scanf("%lld %lld",&st,&ed);
  67.         memset(DP,-1,sizeof(DP));
  68.         num = int2str(ed);
  69.         N = num.length();
  70.         long long res1 = call(0,0,0,true);
  71.  
  72.         memset(DP,-1,sizeof(DP));
  73.         num = int2str(st-1);
  74.         N = num.length();
  75.         long long res2 = call(0,0,0,true);
  76.         printf("%lld\n",res1-res2);
  77.     }
  78.     return 0;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment