生成元(Digit Generator, ACM/ICPC Seoul 2005, UVa1583)*字符串

例题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]);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值