您的位置:首页 > 其它

例题3-5 生成元(Digit Generator, ACM/ICPCSeoul 2005, UVa1583)

2018-02-24 10:25 791 查看
/*例题3-5 生成元(Digit Generator, ACM/ICPCSeoul 2005, UVa1583)
如果x加上x的各个数字之和得到y,就说x是y的生成元。给出n(1≤n≤100000),求最小生成元。无解输出0。例如,n=216,121,2005时的解分别为198,0,1979。
【分析】
本题看起来是个数学题,实则不然。假设所求生成元为m。不难发现m<n。换句话说,只需枚举所有的m<n,看看有没有哪个数是n的生成元。
可惜这样做的效率并不高,因为每次计算一个n的生成元都需要枚举n-1个数。有没有更快的方法?聪明的读者也许已经想到了:只需一次性枚举100000内的所有正整数m,标记“m加上m的各个数字之和得到的数有一个生成元是m”,最后查表即可。*/#include<stdio.h>
#include<string.h>
#define maxn 100005
int ans[maxn];
int main()
{
int T, n;
memset(ans, 0, sizeof(ans));//数组置0
for(int m = 1; m < maxn; m++) { //枚举100005内的所有正整数m
int x = m, y = m;
while(x > 0) { y += x % 10; x /= 10; }//求m加上m的各个数字之和得到的数
if(ans[y] == 0 || m < ans[y]) ans[y] = m;//满足条件就有一个生成元是m或0
}
scanf("%d", &T);
while(T--) {
scanf("%d", &n);
printf("%d\n", ans
);//直接查表输出
}
return 0;
}原文:
For a positive integer N, the digit-sum of N is defined as the sumof N itself and its digits. When M is the digitsum of N, w
4000
e call N a generatorof 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 somenumbers have more than one generator. For example, the generators of 216 are198 and 207.
You are to write a program to find the smallest generator of thegiven integer.
Input
Your program is to read from standard input. The input consists of Ttest 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.
Output
Your program is to write to standard output. Print exactly one linefor 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 anygenerators, print ‘0’.
Sample Input
3
216
121
2005
Sample Output
198
0
1979
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: