Digit sum
描述
原题链接 Digit sum
意思就是给出一个数n,把1~n的每个数的b进制求出,再把每个b进制数的每一位相加求和,最后把每一个和相加求和就是所求的结果。
这个题非常简单,但我提交三次都是运行超时,下面是超时的代码:
//运行超时
#include <iostream>
#include <cstdio>
using namespace std;
int total;
int main()
{
int T,b,n,num=0;
scanf("%d",&T);
while(T--){
total = 0;
scanf("%d%d",&n,&b);
for(int i=1; i<=n; i++){
int tmp = i;
while(tmp){
total += tmp%b;
tmp/=b;
}
}
printf("Case #%d: %d\n",++num,total);
}
return 0;
}
题解只提示先预处理,我稍做一下修改还真过了,难道预处理还能减少时间复杂度,有些郁闷,后来意识到(1≤T≤100000)才明白。
正解:
#include <iostream>
//#include <cstring>
#include <cstdio>
using namespace std;
int a[1000005][10];
int main()
{
int T,n,b,tag=0,tmp;
//memset(dp,0,sizeof(dp));
for(int j=2; j<=10; j++){
for(int i=1; i<=1000000; i++){
tmp = i;
while(tmp){
a[i][j] += tmp%j;
tmp/=j;
}
a[i][j] += a[i-1][j];
}
}
scanf("%d",&T);
while(T--){
scanf("%d%d",&n,&b);
printf("Case #%d: %d\n",++tag,a[n][b]);
}
return 0;
}