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 Xshould not be 0.
Input
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
|
解题思路:用递归遍历出每个位数上的数字,如果当前位数大于a,就对前面到现在的数字进行判断。
#include <stdio.h>
#include <string.h>
const int N = 50;
int begin, endin, flag;
int num[N];
bool judge(int cur) {
int sum = 0;
for (int i = 1; i <= cur; i++) {
sum = sum * 10 + num[i];
sum = sum % cur;
}
return sum?false:true;
}
void dfs(int cur) {
if (cur > endin) {
flag = 1;
return ;
}
for (num[cur] = 0; num[cur] < 10; num[cur]++) {
if (cur >= begin) {
if (judge(cur))
dfs(cur + 1);
}
else
dfs(cur + 1);
if (flag) return;
}
}
int main() {
int cas, t = 1;
scanf("%d", &cas);
while (cas--) {
// Init;
memset(num, 0, sizeof(num));
flag = 0;
scanf("%d%d", &begin, &endin);
int cur = 1;
for (num[cur] = 1; num[cur] < 10; num[cur]++) {
dfs(cur + 1);
if (flag)
break;
}
printf("Case %d: ", t++);
if (flag) {
for (int i = 1; i <= endin; i++)
printf("%d", num[i]);
printf("\n");
}
else
printf("-1\n");
}
return 0;
}