1、定义
按照问题的要求,一一列举所有有可能的解,然后进行判断,若符合要求则采纳这个解,不符合就抛弃。
2、算法实现
第一部分(循环部分):
利用循环把所有有可能的解,一一列举出来。需注意不能遗漏任何一个解,也要避免重复。
要考虑如何设计循环变量、初值、终值和递增值。循环变量是否参与检验。
为了提高解题效率,尽可能的缩小枚举范围。
第二部分(检验);
准确找出判断条件,对每一个解进行检验。
3、枚举算法实例
第一题:分数拆分(Fractions Again?!,UVa 10976)
输入一个正整数k,找到所有的正整数x>=y,使得1/k=1/x+1/y。
样例输入
2
12
样例输出
2
1/2 = 1/6 + 1/3
1/2 = 1/4 + 1/4
8
1/12 = 1/156 + 1/13
1/12 = 1/84 + 1/14
1/12 = 1/60 + 1/15
1/12 = 1/48 + 1/16
1/12 = 1/36 + 1/18
1/12 = 1/30 + 1/20
1/12 = 1/28 + 1/21
1/12 = 1/24 + 1/24
解题思路:由给出的式子,和x>=y,可知,k<y<=2k,通过一一枚举y,求出满足式子的x即可。
代码如下:
#include <iostream>
#include <cstdio>
#include <cstdio>
#include <string>
#include <cmath>
#include <algorithm>
using namespace std;
int main()
{
int k;
while(scanf("%d",&k)!=EOF)
{int cnt = 0;
for(int i=k+1;i<=2*k;i++){
if(k*i%(i-k)==0){
cnt++;
}
}
printf("%d\n",cnt);
for(int i=k+1;i<=2*k;i++){
if(k*i%(i-k)==0){
printf("1/%d = 1/%d + 1/%d\n",k,k*i/(i-k),i);
}
}}
return 0;
}
第二题 除法(Division,UVa 725)
输入正整数n,按从小到大的顺序输出所有形如abcde/fghij = n的表达式,
其中aj恰好为数字09的一个排列(可以有前导0),2<=n<=79。
如果不存在 ,则输出There are no solutions for n.n为0是结束程序。
样例输入
61
62
0
样例输出
There are no solutions for 61.
79546 / 01283 = 62
94736 / 01528 = 62
解题思路:枚举分母从1234~98765 ,用数组a[10]来判断是否重复。
代码如下:
#include <iostream>
#include <cstdio>
#include <cstdio>
#include <string>
#include <cmath>
#include <algorithm>
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
for(int s=0;;s++){
cin >>n;
int flag=0;
if(n==0) break;
if(s>0) printf("\n");
int a[10]={0};
int x,m,j,b,k;
for(int i=1234;i<=98765;i++){
memset(a,0,sizeof(a));
x=i;
for(j=0;j<5;j++){
m=x%10;
if(a[m]==1){
break;
}
a[m]=1;
x=x/10;
}
if(j==5) {
b=i*n;
x=b;
for(k=0;k<5;k++){
if(x>99999) break;
m=x%10;
if(a[m]==1){
break;
}
a[m]=1;
x=x/10;
}
if(k==5) {
printf("%05d / %05d = %d\n",b,i,n);
flag++;
}
}
}
if(flag==0) printf("There are no solutions for %d.\n",n);
}
return 0;
}