Solution for Codeforces 205D - Little Elephant and Interval

Solution #

It’s kinda obvious that we need to write a function F(x)F(x) which solves the problem 1x1\dots x and the answer will be F(r)F(l1)F(r)-F(l-1).

One tricky way to write F(x)F(x) is that we can get the required number by appending the first digit to the end of an arbitrary number. If x is less than 10, the answer is x, otherwise the answer is x without last digit (divide x by 10) plus 9. What’s more, if the last digit is smaller than the first digit we have to decrease the answer by 1.

Code #

#include <bits/stdc++.h>
 
using namespace std;
typedef long long ll;
 
ll cal(ll x){
	if(x<10) return x;
	string st=to_string(x);
	ll ans=9;
	if(st[0]>st.back()) ans--;
	ans+=x/10;
	return ans;
}
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
	ll l,r;
	cin>>l>>r;
	cout<<cal(r)-cal(l-1);
    return 0;
}