UVA-725 Division (简单暴力枚举)

版权声明:个人学习笔记记录 https://blog.csdn.net/Ratina/article/details/83997929

刘汝佳书上例举的典型暴力枚举题~
暴力枚举题要经过分析来尽量减少不必要的枚举。

题目:UVA-725

题目描述:
输入正整数N,从小到大输出所有形如abcde/fghij=N的表达式,其中a-j恰好为数字0-9的一个排列(可以有前导0)(2=<n<=79)
如果没有符合表达式,输出"There are no solutions for N."

思路:
①通过从小到大枚举abcde,得到abcde*N=fghij,再检查两者是否符合0~9的一个排列,减少了枚举量。
②只需从1234枚举到98765,同时当abcde * N>98765,即可结束枚举,以此减少枚举量。

Ps.注意输出格式的坑,输出4位数时前面要加上前导0,每两个输出间一个空行,最后一个输出后无空行。

以下代码:

#include<iostream>
using namespace std;
bool judge(int a,int b)   //判断是否符合0~9的一个排列
{
	int num[10] = {0};
	if (a < 10000)
		num[0]++;
	while (1)
	{
		num[a % 10]++;
		a = a / 10;
		if (a == 0)
			break;
	}
	if (b < 10000)
		num[0]++;
	while (1)
	{
		num[b % 10]++;
		b = b / 10;
		if (b == 0)
			break;
	}
	for (int i = 0; i <= 9; i++)
	{
		if (num[i] != 1)
			return false;
	}
	return true;
}
int main()
{
	int N;
	int kase = 0;
	while (cin >> N && N != 0)
	{
		if (kase++)         //每两个输出间一个空行
			cout << endl;
		int i;
		bool flag = false;
		for (i = 1234; i <= 98765; i++)
		{
			if (i*N > 98765)
				break;
			if (judge(i,i*N))
			{
				if (i*N < 10000)
					putchar('0');
				cout << i * N << " / ";
				if (i < 10000)
					putchar('0');
				cout<< i << " = " << N << endl;
				flag = true;
			}
		}
		if (flag == false)
			cout << "There are no solutions for " << N << "." << endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Ratina/article/details/83997929
今日推荐