码迷,mamicode.com
首页 > 其他好文 > 详细

UVa1583 Digit Generator

时间:2015-02-21 00:15:15      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

 

For a positive integer N <tex2html_verbatim_mark>, the digit-sum of N <tex2html_verbatim_mark>is defined as the sum of N <tex2html_verbatim_mark>itself and its digits. When M <tex2html_verbatim_mark>is the digitsum of N <tex2html_verbatim_mark>, we call N <tex2html_verbatim_mark>a generator of M <tex2html_verbatim_mark>.

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.

 

Input 

Your program is to read from standard input. The input consists of T <tex2html_verbatim_mark>test cases. The number of test cases T<tex2html_verbatim_mark>is given in the first line of the input. Each test case takes one line containing an integer N <tex2html_verbatim_mark>, 1技术分享N技术分享100, 000 <tex2html_verbatim_mark>.

 

Output 

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 <tex2html_verbatim_mark>for each test case. If N <tex2html_verbatim_mark>has multiple generators, print the smallest. If N <tex2html_verbatim_mark>does not have any generators, print 0.

The following shows sample input and output for three test cases.

 

Sample Input 

 

3 
216 
121 
2005

 

Sample Output 

 

198 
0 
1979

 

这道题本身很简单,但直接枚举每个数字肯定会效率低下,预先处理打一张表效率会高很多。

#include <stdio.h>
#include <string.h>
#define MAXN 100000

int ans[MAXN];

int main()
{
  int T, n;
  memset(ans, 0, sizeof(ans));
  for(int m = 1; m < MAXN; m++)   //init
  {
    int x = m, y = m;
    while(x > 0)
    {
      y += x % 10;
      x /= 10;
    }
    if(!ans[y] || m < ans[y]) ans[y] = m;
  }
  scanf("%d", &T);
  while(T--)
  {
    scanf("%d", &n);
    printf("%d\n", ans[n]);
  }
  return 0;
}

UVa1583 Digit Generator

标签:

原文地址:http://www.cnblogs.com/cuichen/p/4296769.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!