UVa 725 暴力搜索

UVa 725
输入n个正整数,按照从小到大的顺序输出形如abcde / fghij = n的表达式,其中a-j恰好为数字0-9的一个排列(可以有前导0)。

只需要枚举第一个数,范围是12345-98765,已知n,找到能除尽n的第二个数,检查这2个数是否满足0-9的排列即可。

检查函数中将i,j格式化输入到字符串中,排序后,检查字符串是否一一对应。

#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
bool check(int i, int j) {
    
    
	char s[11];
	sprintf(s, "%05d%05d", i, j);
	sort(s, s + 10);
	for (int i = 0; i < 10; ++i) {
    
    
		if (s[i] != '0' + i) {
    
    
			return false;
		}
	}
	return true;
}
int main() {
    
    
	int n;
	bool is = false;
	while (~scanf("%d", &n) && n) {
    
    
		if (is) {
    
    
			printf("\n");
		}
		is = true;
		bool ans = false;
		for (int i = 10000; i < 100000; ++i) {
    
    
			if (i % n == 0 && check(i, i / n)) {
    
    
				ans = true;
				printf("%d / %05d = %d\n", i, i / n, n);
			}
		}
		if (!ans) {
    
    
			printf("There are no solutions for %d.\n", n);
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/WxqHUT/article/details/109001836