UVA1583 Digit Generator
问题描述:
For a positive integer N , the digit-sum of N is defined as the sum of N itself and its digits. When M is the digitsum of N , we call N a generator of M .
For example, the digit-sum of 245 is 256 (= 245 + 2 + 4 + 5). Therefore, 245 is a generator of 256.
Not surprisingly, some numbers do not have any generators and some numbers have more than one generator. For example, the generators of 216 are 198 and 207.
You are to write a program to find the smallest generator of the given integer.
输入:
Your program is to read from standard input. The input consists of T test cases. The number of test cases T is given in the first line of the input. Each test case takes one line containing an integer N , 1
N
100, 000 .
输出:
Your program is to write to standard output. Print exactly one line for each test case. The line is to contain a generator of N for each test case. If N has multiple generators, print the smallest. If N does not have any generators, print 0.
The following shows sample input and output for three test cases.
解题思路:
很容易得出对于正整数n,n如果存在生成元m,则必有m < n.
枚举0到100000的所有数m
使m加上m的各个位数之和得到数n,则n的可能生成元是m
解题关键:
利用数组构成正整数n和其最小生成元的一个映射
AC:
#include "iostream" #include "cstdio" #include "cstring" using namespace std; const int MAX_N = 100001; int n; int T; int ans[MAX_N]; int main(int argc, char const *argv[]) { memset(ans, 0, sizeof(ans)); for(int i = 0; i < MAX_N; i++) { int x = i; int y = i; while(y > 0) { x += y % 10; y /= 10; } if(ans[x] == 0 || ans[x] > i) ans[x] = i; } scanf("%d", &T); while(T--) { scanf("%d", &n); printf("%d\n", ans[n]); } return 0; }
总结:
对于任意的输入n,所有数的最小生成元是不变的且是一一映射的,所以在输入前构建出所有数到对应的最小生成元的映射是解题的关键。
此题虽然看似可以对任意的n采用一次循环搜索,但其效率明显低于采用保存映射的策略。
保存映射是一个典型的用空间换时间的策略

浙公网安备 33010602011771号