【Uva】725-Division

1、题目

Write a program that finds and displays all pairs of 5-digit numbers that between them use the digits 0 through 9 once each, such that the first number divided by the second is equal to an integer N N N, where 2 ≤ N ≤ 79 2 ≤ N ≤ 79 2N79. That is,
a b c d e f g h i j = N \frac{abcde}{fghij} = N fghijabcde=N
where each letter represents a different digit. The first digit of one of the numerals is allowed to be
zero.

Input

Each line of the input file consists of a valid integer N N N. An input of zero is to terminate the program.

Output

Your program have to display ALL qualifying pairs of numerals, sorted by increasing numerator (and,
of course, denominator).

Your output should be in the following general form:

xxxxx / xxxxx = N
xxxxx / xxxxx = N
.
.

In case there are no pairs of numerals satisfying the condition, you must write ‘There are no
solutions for N.
’. Separate the output for two different values of N N N by a blank line.

Sample Input

61
62
0

Sample Output

There are no solutions for 61.

79546 / 01283 = 62
94736 / 01528 = 62

725 - Division

2、题意

输入正整数 n n n,按从小到大的顺序输出所有形如 a b c d e / f g h i j = n abcde/fghij = n abcde/fghij=n 的表达式,其中 a a a ~ j j j 恰好为数字 0 ~ 9 的一个排列(可以有前导0), 2 ≤ n ≤ 79 2 \le n \le 79 2n79

3、分析

暴力枚举,但是没有必要枚举 0 ~ 9 的所有排列,只需要枚举 f g h i j fghij fghij 就可以算出 a b c d e abcde abcde,然后判断是否所有数字的偶不相同即可。枚举量从 10! - 3628800 降低至不到1万,且当 a b c d e abcde abcde f g h i j fghij fghij 加起来超过 10 位时可以终止枚举。

4、代码实现

#include
#include
#include
using namespace std;

int main() {
  int n, kase = 0;
  char buf[99];
  while(scanf("%d", &n) == 1 && n) {
    int cnt = 0;
    if(kase++) printf("\n");
    for(int fghij = 1234; ; fghij++) {
      int abcde = fghij * n;
      sprintf(buf, "%05d%05d", abcde, fghij);
      if(strlen(buf) > 10) break;
      sort(buf, buf+10);
      bool ok = true;
      for(int i = 0; i < 10; i++)
        if(buf[i] != '0' + i) ok = false;
      if(ok) {
        cnt++;
        printf("%05d / %05d = %d\n", abcde, fghij, n);
      }
    }
    if(!cnt) printf("There are no solutions for %d.\n", n);
  }
  return 0;
}

你可能感兴趣的:(#,Uva,枚举)