Super Number
Input: Standard Input
Output: Standard Output
Time Limit: 3 Seconds
Don't you think 162456723 very special? Look at the picture below if you are unable to find its speciality. (a | b means �b is divisible by a�)

Figure: Super Numbers
Given n, m (0 < n < m < 30), you are to find a m-digit positive integer X such that for every i (n <= i <= m), the first i digits of X is a multiple of i. If more than one such X exists, you should output the lexicographically smallest one. Note that the first digit of X should not be 0.
Input
The first line of the input contains a single integer t(1 <= t <= 15), the number of test cases followed. For each case, two integers n and m are separated by a single space.
Output
For each test case, print the case number and X. If no such number, print -1.
Sample Input�������������������������� Output for Sample Input
2 1 10 3 29 | Case 1: 1020005640 Case 2: -1
|
题目大意:
要求你求出一个超级数字,超级数字的定义如下:
由m位,所有前i位,都能被数字i整除(n <= i <= m),如果超级数字不止一个要求输出字典序最小的超级数字。
注意:超级数字的第一位不能为0
举个例子:
输入
1 10
输出
1020005640
1 % 1 = 0
10 % 2 = 0
102 % 3 = 0
1020 % 4 = 0
10200 % 5 = 0
102000 % 6 = 0
1020005 % 7 = 0
...
1020005640 % 10 = 0
所以当n=1,m=10时,1020005640是超级数字。
解析:数字最多有30位需要用数组进行保存,回溯求解,先1~9,枚举出第一位,再用回溯枚举出剩下的位数,每个位数的值为0~9,注意当cur < n时可以直接枚举下一位,当cur >= n时,需要判断前cur位是否能被cur整除,但是这个数字可能非常大(最多30位),所以要模拟除法的过程,步骤如下:
1.从首位开始对cur求余数
2.(余数*10+下一位) % cur
3.重复2的操作,直到当前的位数 == cur结束。
#include <cstdio>
#include <cstring>
using namespace std;
bool ok;
int m,n;
int num[35];
inline int judge(int cur) {
int sum = 0;
for(int i = 1; i <= cur; i++) {
sum = (sum * 10 + num[i]) % cur;
}
return sum;
}
inline void dfs(int cur) {
if(cur == m+1) {
ok = true;
return ;
}
for(int i = 0; i < 10; i++) {
num[cur] = i;
if(cur < n || (cur >= n && !judge(cur)) ) {
dfs(cur+1);
}
if(ok) {
return ;
}
}
}
int main() {
int t;
int cas = 1;
scanf("%d",&t);
while(t--) {
scanf("%d%d",&n,&m);
for(int i = 1; i < 10; i++) {
num[1] = i;
ok = false;
dfs(2);
if(ok) {
break;
}
}
printf("Case %d: ",cas++);
if(ok) {
for(int i = 1; i <= m; i++) {
printf("%d",num[i]);
}
printf("\n");
}else {
printf("-1\n");
}
}
return 0;
}