目录
一、题目链接
UVA725 除法 Division - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
二、原题解读
-
原题
Division
题目描述
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, where 2≤N≤79. That is,abcde/fghij=N,where each letter represents a different digit. The first digit of one of the numerals is allowed to be zero.
输入描述
Each line of the input file consists of a valid integer N. An input of zero is to terminate the program.
输出描述
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 by a blank line.
样例
输入
61 62 0
输出
There are no solutions for 61. 79546 / 01283 = 62 94736 / 01528 = 62
-
题意
用0到9这十个数无重复地组成两个五位整数,可以有前导零,判断能否使两数之商为目标值,若能,输出该组合,若不能,输出特定语句。本题为多组输入,对于每次访问,应输出满足条件的所有组合,组合输出按照从小到大的顺序。
三、解题过程
-
思路
从十个数中搜索出五个数组成分母,若分母与目标值的乘积的各个数位恰为未选的五个数字,则满足条件,输出该组合。
其中,判断时利用集合set,将组成分子分母的十个数字存入set,看其size是否为10,若s为10,则满足条件,否则不满足。
多组输入,输出时格式要求十分严格,要注意每组输出之后都要换行,=,/ 两边都有空格,输出句子的最后有点号。
-
代码
#include<bits/stdc++.h>
using namespace std;
void dfs(int dp);
int n,a[]={0,1,2,3,4,5,6,7,8,9};
int pt=0,c[11]={0};
int main()
{ while(cin>>n&&n!=0)
{ pt=0;
dfs(0);
if(pt==0) //标志量,看是否有满足条件的结果
cout<<"There are no solutions for "<<n<<".\n";
cout<<"\n";
}
}
void dfs(int dp)
{ if(dp==5)
{ int pp=(c[0]*10000+c[1]*1000+c[2]*100+c[3]*10+c[4])*n;
int pf=0;
if(pp<=10000||pp>=100000) return; //利用分子是五位数进行剪枝
set<int> ss;
ss.insert(pp/10000);
ss.insert((pp/1000)%10);
ss.insert((pp/100)%10);
ss.insert((pp/10)%10);
ss.insert(pp%10);
for(int ii=0;ii<=4;ii++)
ss.insert(c[ii]);
if(ss.size()==10) pf=1; //判断是否无重复地组成了两个数
if(pf==1) //输出
{ cout<<pp/10000<<(pp/1000)%10<<(pp/100)%10<<(pp/10)%10<<pp%10;
cout<<" / ";
printf("%05d",c[0]*10000+c[1]*1000+c[2]*100+c[3]*10+c[4]);
cout<<" = ";
cout<<n<<"\n";
pt=1;
}
return;
}
for(int i=0;i<=9;i++)
if(b[i]!=1)
{ b[i]=1;
c[dp]=a[i];
dfs(dp+1);
b[i]=0;
}
}