题目:UVA10624 - Super Number(dfs)
题目大意:给你n和m要求找出这种m位数,从第n位到第m位都满足前i位是能够被i整除,假设没有这种数,输出-1.有多个就输出字典序最小的那个。
解题思路:将每一个位置都用0..9枚举一下,注意第一个字符不能是0,然后dfs推断每一个位置是否都满足要求。注意这里是会爆long long的,所以要取模一下。本来以为这种做法会超时的,结果居然过了,预计是例子数少,并且找不到的情况也比較少。
代码:
#include <cstdio> #include <cstring> const int N = 35; typedef unsigned long long ll; int num[N]; int m, n; bool judge (int cur) { ll sum = 0; for (int i = 0; i <= cur; i++) { sum = sum * 10 + num[i]; if (i > 17) sum = sum % (cur + 1); } sum = sum % (cur + 1); return sum ?false : true; } bool dfs (int cur) { if (cur == m) return true; for (int i = 0; i < 10; i++) { if (!cur && !i) continue; num[cur] = i; if (cur < n - 1 || judge(cur)) { if (dfs (cur + 1)) return true; } } return false; } int main () { int t; scanf ("%d", &t); for (int i = 1; i <= t; i++) { scanf ("%d%d", &n, &m); printf ("Case %d: ", i); if (!dfs(0)) printf ("-1 "); else { for (int j = 0; j < m; j++) printf ("%d", num[j]); printf (" "); } } return 0; }