【牛客网NC13221数码】题解

题目链接

题目

给定两个整数 l 和 r ,对于所有满足1 ≤ l ≤ x ≤ r ≤ 10^9 的 x ,把 x 的所有约数全部写下来。对于每个写下来的数,只保留最高位的那个数码。求1~9每个数码出现的次数。

image

思路

显然数论分块

然后统计一下每一块内1到9出现的情况乘上 \(n/l\) 即可

Code

// Problem: 数码
// Contest: NowCoder
// URL: https://ac.nowcoder.com/acm/problem/13221
// Memory Limit: 2 MB
// Time Limit: 13221000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

#include<bits/stdc++.h>
using namespace std;
#define int long long
inline int read(){int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;
ch=getchar();}while(ch>='0'&&ch<='9'){x=(x<<1)+
(x<<3)+(ch^48);ch=getchar();}return x*f;}
//#define M
//#define mo
//#define N
int n, m, i, j, k, T; 
int l, r, a[15], ten[15]; 

int wei(int x)
{
	int ans=0; 
	while(x) x/=10, ++ans; 
	// printf("%lld\n", ans); 
	return ans; 
}

int ji(int n, int k)
{
	if(!n) return 0; 
	int w=wei(n);
	// printf("lld\n", w); 
	// return 0;  
	int ans=(ten[w-1]-1)/9; 
	int f=n/ten[w-1]; 
	if(k<f) ans+=ten[w-1]; 
	if(k==f) ans+=n%ten[w-1]+1; 
	return ans; 
}

int suan(int l, int r, int k)
{
	// printf("%lld %lld %lld\n", l, r, k); 
	// return 0; 
	return ji(r, k)-ji(l-1, k); 
}

void calc(int n, int p)
{
	int l, r; 
	for(l=1; l<=n; l=r+1)
	{
		r=min(n, n/(n/l)); 
		for(j=1; j<=9; ++j)	a[j]+=p*(n/l)*suan(l, r, j); 
	}
}

signed main()
{
//	freopen("tiaoshi.in", "r", stdin); 
//	freopen("tiaoshi.out", "w", stdout); 
	for(i=ten[0]=1; i<=14; ++i) ten[i]=ten[i-1]*10; 
	l=read(); r=read(); 
	calc(r, 1); calc(l-1, -1);
	for(i=1; i<=9; ++i) printf("%lld\n",  a[i]); 
	return 0; 
}

总结

首先看到这道题,把式子列出来,很容易发现是数论分块

然后每个数出现的个数想一下就打了

posted @ 2022-07-29 13:20  zhangtingxi  阅读(82)  评论(0编辑  收藏  举报