binary search combinatorics dp *1500

Please click on ads to support us..

Python Code:

def find(s):
    n = len(s)
    x = int(s)
    if (x < 10):
        return x
    ans = x // 10 - 1
    ans = ans + 9
    if (s[0] <= s[n-1]):
        ans = ans + 1
    return ans
 
l, r = map(int, input().split())
l = l - 1
l = str(l)
r = str(r)
count1 = find(l)
count2 = find(r)
print(count2 - count1)

C++ Code:

#include <iostream>
#include <cstring>

using namespace std;

typedef long long ll;

ll dp[10][20][2];

ll solve(string &num,int i,int j,int k)
{
    int n = num.size();
    
    if(dp[i][j][k]!=-1) return dp[i][j][k];
    
    if(j == 1){
       if(i == 0 && k == 1){
           return num[n-1] - '0';
       }
       if( i == 0 && k == 0 ) return 9;
       if ( k == 1 ) return i<=(num[n-1]-'0');
       
       return 1;
    }
    
    int ub = (k == 0)?9:num[n-j]-'0';
    ll ans = 0;
    
    for(int l = 0; l<=ub; l++)
    {  
       int f = (i == 0)?l:i;
       int tight = (k == 1)?l == ub:0;
       ans += solve(num,f,j-1,tight);
    }
    
    return dp[i][j][k] = ans;
    
}

int main()
{
    ll l1,r;
    
    cin>>l1>>r;
    
    ll l = l1-1;
    
    string rn = to_string(r);
    string ln = to_string(l);
    
    memset(dp,-1,sizeof(dp));
    
    ll fff = solve(rn,0,rn.size(),1);
    
    memset(dp,-1,sizeof(dp));
    ll lll = solve(ln,0,ln.size(),1);
    
    cout<<fff-lll;
}


Comments

Submit
0 Comments
More Questions

21. Merge Two Sorted Lists
203. Remove Linked List Elements
733. Flood Fill
206. Reverse Linked List
83. Remove Duplicates from Sorted List
116. Populating Next Right Pointers in Each Node
145. Binary Tree Postorder Traversal
94. Binary Tree Inorder Traversal
101. Symmetric Tree
77. Combinations
46. Permutations
226. Invert Binary Tree
112. Path Sum
1556A - A Variety of Operations
136. Single Number
169. Majority Element
119. Pascal's Triangle II
409. Longest Palindrome
1574A - Regular Bracket Sequences
1574B - Combinatorics Homework
1567A - Domino Disaster
1593A - Elections
1607A - Linear Keyboard
EQUALCOIN Equal Coins
XOREQN Xor Equation
MAKEPAL Weird Palindrome Making
HILLSEQ Hill Sequence
MAXBRIDGE Maximise the bridges
WLDRPL Wildcard Replacement
1221. Split a String in Balanced Strings