首页 > ACM题库 > HDU-杭电 > HDU 1663 The Counting Problem-数学相关-[解题报告] C++
2013
12-21

HDU 1663 The Counting Problem-数学相关-[解题报告] C++

The Counting Problem

问题描述 :

Given two integers a and b, we write the numbers between a and b, inclusive, in a list. Your task is to calculate the number of occurrences of each digit. For example, if a = 1024 and b = 1032, the list will be

1024 1025 1026 1027 1028 1029 1030 1031 1032

there are ten 0′s in the list, ten 1′s, seven 2′s, three 3′s, and etc.

输入:

The input consists of up to 500 lines. Each line contains two numbers a and b where 0 < a, b < 100000000. The input is terminated by a line `0 0′, which is not considered as part of the input.

输出:

For each pair of input, output a line containing ten numbers separated by single spaces. The first number is the number of occurrences of the digit 0, the second is the number of occurrences of the digit 1, etc.

样例输入:

1 10
44 497
346 542
1199 1748
1496 1403
1004 503
1714 190
1317 854
1976 494
1001 1960
0 0

样例输出:

1 2 1 1 1 1 1 1 1 1
85 185 185 185 190 96 96 96 95 93
40 40 40 93 136 82 40 40 40 40
115 666 215 215 214 205 205 154 105 106
16 113 19 20 114 20 20 19 19 16
107 105 100 101 101 197 200 200 200 200
413 1133 503 503 503 502 502 417 402 412
196 512 186 104 87 93 97 97 142 196
398 1375 398 398 405 499 499 495 488 471
294 1256 296 296 296 296 287 286 286 247

本来是个搜索题,但是发现用数学的方法做的,队友讲的

代码:

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
int n,m,ansa[11],ansb[11];
void GetNum(int num,int *ans)
{
    for(int i=1;i<=9;i++)
    {
	int x=num,index=10,now=10;
	int sum=x/10;
	if(i<=x%10)
	    sum++;
	while(x)
	{
	    if(index*10>x)
	    {
		if(i==x/index%10)
		    sum+=x%index+1;
		else if(i<x/index%10)
		    sum+=now;
		break;
	    }
	    if(i<x/index%10)
		sum+=(x/index/10+1)*now;
	    else
		sum+=(x/index/10)*now;
	    if(i==x/index%10)
		sum+=x%index+1;
	    now*=10;
	    index*=10;
	}	
	ans[i]=sum;
    }
    int i=1,k=0,r;
    int x=num;
    while(x>=10)
    {
	r=x%10;
	x/=10;
	if(r)
	    ans[0]+=i*x;
	else
	    ans[0]+=(x-1)*i+k+1;
	k+=r*i;
	i*=10;
    }
}
int main()
{
    while(scanf("%d%d",&n,&m)&&(n+m))
    {
	memset(ansa,0,sizeof(ansa));
	memset(ansb,0,sizeof(ansb));
	if(n>m)
	    swap(n,m);
	n--;
	GetNum(m,ansb);
	GetNum(n,ansa);
	printf("%d",ansb[0]-ansa[0]);
	for(int i=1;i<10;i++)
	    printf(" %d",ansb[i]-ansa[i]);
	printf("\n");
    }
    return 0;
}

解题报告转自:http://blog.csdn.net/z309241990/article/details/9164523


  1. 有两个重复的话结果是正确的,但解法不够严谨,后面重复的覆盖掉前面的,由于题目数据限制也比较严,所以能提交通过。已更新算法

  2. 博主您好,这是一个内容十分优秀的博客,而且界面也非常漂亮。但是为什么博客的响应速度这么慢,虽然博客的主机在国外,但是我开启VPN还是经常响应很久,再者打开某些页面经常会出现数据库连接出错的提示

  3. #include <cstdio>

    int main() {
    //answer must be odd
    int n, u, d;
    while(scanf("%d%d%d",&n,&u,&d)==3 && n>0) {
    if(n<=u) { puts("1"); continue; }
    n-=u; u-=d; n+=u-1; n/=u;
    n<<=1, ++n;
    printf("%dn",n);
    }
    return 0;
    }