您的位置:首页 > 其它

暴力枚举

2016-04-18 12:08 281 查看
题目如下:





解法 1

1、用一个10维数组match记录 构建每个数字所需要的 火柴数。 比如match[0] = 6 : 表示构建0需要6根火柴。

2、用一个二维数组res 存储 某行 + 某列 需要的火柴数目。比如: res[0][1] = 14 : 表示 0 + 1 = 1 ;这个等式需要消耗14根火柴

3、定义一个结构体数组,结构体如下

struct mat{
int row; //行号
int col; //列号
}


在计算的过程中,每发现一对的火柴数符合要求,就记录下行号和列号,存储到数组中。

4、计算完之后,输出结构体数组。

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
struct mat
{
int row;    //行号
int col;    //列号
};
#define SUM 18
#define MAX 200
int main()
{
// 对应序号所需要的火柴数量
int match[MAX] = { 6, 2, 5, 5, 4, 5, 6, 3, 7, 6 };
for (int i = 10; i < MAX; i++)
{
int tmp = 0;
int j = i;
while (j)
{
tmp += match[j % 10];
j = j / 10;
}
match[i] = tmp;
}
int arr[MAX][MAX] = { 0 };
vector<mat> res;
for (int i = 0; i < MAX; i++)
{
for (int j = 0; j < MAX; j++){
if (i + j > MAX)
continue;
arr[i][j] = match[i] + match[j] + match[i+j] + 4;
if (arr[i][j] == SUM)
{
mat tmp = { i, j };
res.push_back(tmp);
}
}
}
for (auto it = res.begin(); it != res.end(); it++)
{
cout << it->row << " + " << it->col << " = " << SUM << endl;
}
return 0;
}


解法 2

上述解法的空间复杂度过高,容易爆栈。不需要保存计算结果,当满足要求时立即输出即可。

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

// 对应序号所需要的火柴数量
int match[10] = { 6, 2, 5, 5, 4, 5, 6, 3, 7, 6 };

int fun(int val)
{
int num = 0;

// 当val == 0时
while (val/10 != 0) // 满足条件时,表示val此时至少是个2位数
{
num += match[val % 10];
val /= 10;
}
num += match[val];

return num;
}

int main()
{
int matNum;
cin >> matNum;
int k;
int sum = 0;
for (int i = 0; i <= 11111; i++)
{
for (int j = 0; j <= 11111; j++)
{
k = i + j;
if (fun(i) + fun(j) + fun(k) == matNum - 4)
{
printf(" %d + %d = %d \n", i, j, k);
sum++;
}
}
}
cout << sum << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: