1.如果对每一个测试数据,都从自身开始向下查找其生成元,这样也能做出来。。。。
但是!!!!会超时。。每来一个查一次。。。明显太慢了。。
2.但是提上给了数据范围,查找生成元的最大数是10000,那可以把10000之前的数,做一个最小生成元表。
测试数据时,查表就好。
第一个代码是 TE 的:(很长有木有。。。)
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cctype>
using namespace std;
int main()
{
int T;
scanf("%d",&T);
int sheng[105];//
while(T--)
{
memset(sheng,0,sizeof(sheng));
int n;
scanf("%d",&n);
int i = 0;
int m;
for(m = n;m > 0;m--)
{
int x = m,sum = 0;
while(x > 0)
{
sum += x%10;
x/= 10;
}
if(n == sum+m)
sheng[i++] = m;
}
if(sheng[0] == 0)
printf("0\n");
else//找最小的生成元
{
int min = 100000;
for(int j = 0;j < i;j++)
{
if(sheng[j] < min)
min = sheng[j];
}
printf("%d\n",min);
}
}
return 0;
}
第二个代码是 AC 代码:
对了。。。数组开大别放int main里边。。。会爆栈
(比方说开100005)
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cctype>
using namespace std;
int dig[100005];
int main()
{
int T,n;
memset(dig,0,sizeof(dig));
//计算从1到100005的生成元 生成的数
for(int m = 1;m < 100005;m++)
{
int x = m,y = m;
while(x > 0)
{
y += x%10;
x /= 10;
}
if(dig[y] == 0||m < dig[y])
dig[y] = m;
}
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
printf("%d\n",dig[n]);
}
return 0;
}