codeforces 204A Little Elephant and Interval(数位分解)

题意,给你两个数l,r。求从l-r中有多少个数字满足首位=末位。(看note的那些数字都是首位=末位的数字)

由于数据上限1e18,可以用ll存储,直接开ll,然后for循环i遍历1-18位,内部for循环j遍历1-9的数字。

然后定义一个low代表下界,high代表上界。low=max(l,10^(i-1)),这里max的作用是不统计1-l这些数有多少个符合要求。

上界则为min(r,2*10^(i-1)-1)

例如i=2,j=1时,可以计算100-max(r,199)中,有多少个数字满足首位=末位。计算方法是先用while循环使个位数=百位数,然后做差。

ans+=(high-low)/10+1

ans中的这个+1代表中间全是0的数字(在上述例子中为101)

#include <bits/stdc++.h>
using namespace std;
#define ll long long
int main(){
	ll l,r,ten=1,ans=0;
	cin>>l>>r;
	for(int i=1;i<=18;i++){
		for(int j=1;j<=9;j++){
			ll low=max(l,j*ten),high=min(r,(j+1)*ten-1);
			while(low%10!=j)	low++;
			while((high+10)%10!=j)	high--;
			if(high>=low)	ans+=(high-low)/10+1;
		}
		ten*=10;
	}
	cout<<ans;
}

猜你喜欢

转载自blog.csdn.net/qq_41643650/article/details/84206280