UVA - 725 Division (暴力求解法)

本文提供了一个解决UVA-725问题的C++实现方案,通过检查每个可能的除法组合来确保0到9的数字恰好各使用一次,并展示了完整的代码及注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接: https://vjudge.net/problem/UVA-725


#include <iostream>
#include <cstring>
using namespace std;
int n;
int a[10];
// a[10]用来记录 0~9出现的次数 
// y 是被除数,x是除数,n是商
// 先讨论 x,如果 x 只有 4 位(有前置0),再判断y之前,先进行a[0]++ 
bool CheckSolution(int x, int y, int &flag) //flag 用于标记是否需要输出前导 0 
{
	memset(a, 0, sizeof(a));
	int digit_x = 0;
	while (x)
	{
		digit_x++;
		int temp = x % 10;
		if (a[temp]) return false;
		a[temp]++;
		x /= 10;
	}
	if (digit_x == 4)
	{
		flag = 1;
		if (a[0]) return false;
		a[0]++;
	}
	while(y)
	{
		int temp = y % 10;
		if (a[temp])
		return false;
		a[temp]++;
		y /= 10;
	}
	for (int i = 0; i < 10; i++)
	if (a[i] != 1) return false;
	return true; 
	
}
int main()
{
//	freopen("D:\\input.txt", "r", stdin);
//	freopen("D:\\output.txt", "w", stdout);
	bool is_output;
	int kase;
	while (cin >> n && n)
	{
		if (kase++) cout << endl;
		is_output = false;
		for (int i = 1234; i <= 98765 / n ; i++)
		{
			int flag = 0;
			if ( CheckSolution(i, i * n, flag) )
			{
				cout << i * n << " / ";
				if (flag) cout << "0";
				cout << i << " = " << n << endl;
				is_output = true;
			}
		}
		if (!is_output) cout << "There are no solutions for " << n << "." << endl; 
	}
	return 0;
} 


这题出现过一次PE,原因是:

一般最后一组数据的末尾是不会有换行的,仅仅是相邻两组数据的输出之间有换行分离

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值