例题3-5 生成元(Digit Generator, ACM/ICPC Seoul 2005, UVa1583)
如果x加上x的各个数字之和得到y,就说x是y的生成元。给出n(1≤n≤100000),求最小 生成元。无解输出0。
Input
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.
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 for each test case. If N has multiple generators, print the smallest. If N does
not have any generators, print ‘0’.
例如,n=216,121,2005时的解分别为198,0,1979。
【分析】本题看起来是个数学题,实则不然。假设所求生成元为m。不难发现m<n。换句话说, 只需枚举所有的m<n,看看有没有哪个数是n的生成元。 可惜这样做的效率并不高,因为每次计算一个n的生成元都需要枚举n-1个数。有没有更快的方法?聪明的读者也许已经想到了:只需一次性枚举100000内的所有正整数m,标记“m加上m的各个数字之和得到的数有一个生成元是m”,最后查表即可。
#include<bits/stdc++.h>
using namespace std;
#define maxn 100005
int ans[maxn];
int main()
{
int t,n;
memset(ans,0,sizeof(ans));//将ans数组所有值设为0
for(int m=1;m<maxn;m++)
{
int x=m,y=m;//m是y的生成元
while(x>0){
y+=x%10;
x/=10;
}
if(ans[y]==0||m<ans[y]) ans[y]=m;//保证ans[]下保存的生成元m最小
}
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
printf("%d\n",ans[n]);
}
}