枚舉!很暴力
- 坑爹的奧數
- 炸彈人
- 火柴棍等式
- 數的全排列
坑爹的奧數
枚舉算法的思想,把所有可能的情況全列出
最簡單的枚舉算法:計算 _3 * 6528 = 3_ * 8265
,填入相同的數
for (int i = 1; i < 10; i++) {
if((i * 10 + 3) * 6528 == (30 + i) * 8265){
cout << i;
}
}
炸彈人
#:牆
G:敵人
.:空地
Question:輸入地圖,計算在哪個空地放置炸彈可以消滅最多的敵人
#include<iostream>
using namespace std;
/* #牆 .空地 G敵人 */
int main() {
char a[20][20]; //假設地圖大小小於 20 * 20
int m, n; //n 行 m 列
int max = 0;
int p, q;
cout << "input m, n: ";
cin >> m >> n;
cout << "input map: " << endl;
//讀入 n 行字符,即讀入地圖
for (int i = 0; i < n; i++) {
cin >> a[i];
}
//雙重循環 枚舉地圖的每一個點
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int sum = 0; //可以消滅的敵人數目 sum
int x, y;
//若爲平地 . 可安放炸彈
if (a[i][j] == '.') {
//向上統計可以消滅的敵人數目
x = i;
y = j;
while (a[x][y] != '#') {
if (a[x][y] == 'G') {
sum++;
}
x--;
}
//向下統計
x = i;
y = j;
while (a[x][y] != '#') {
if (a[x][y] == 'G') {
sum++;
}
x++;
}
//向左統計
x = i;
y = j;
while (a[x][y] != '#') {
if (a[x][y] == 'G') {
sum++;
}
y--;
}
//向右統計
x = i;
y = j;
while (a[x][y] != '#') {
if (a[x][y] == 'G') {
sum++;
}
y++;
}
}
if (sum > max) {
max = sum;
p = i;
q = j;
}
}
}
cout << "將炸彈放在(" << p << "," << q << ")處,最多可以消滅 " << max << " 個敵人";
return 0;
}
輸入示例:(可以一行一行的複製)
13 13
#############
#GG.GGG#GGG.#
###.#G#G#G#G#
#.......#..G#
#G#.###.#G#G#
#GG.GGG.#.GG#
#G#.#G#.#.###
##G...G.....#
#G#.#G###.#G#
#...G#GGG.GG#
#G#.#G#G#.#G#
#GG.GGG#G.GG#
#############
運行結果:
火柴棍等式
0:6根火柴
1:2根
2:5根
3:5根
4:4根
5:5根
6:6根
7:3根
8:7根
9:6根
+、=:2根
例如:現在小恆手中有 14 根火柴,則可以拼成兩個不同的等式 0+1=1 和 1+0=1 (必須用完所有火柴)
Question:假設現在小恆手上有 m 根 (m<24) 火柴棍,那麼小恆可以拼出多少個不同的形如 A+B=C 的等式呢?(限時 1 秒)
#include<iostream>
using namespace std;
int fun(int);
int main() {
int num;
cout << "input num: ";
cin >> num;
num = num - 4; //除去 + 和 =
for (int a = 0; a <= 1111; a++) {
for (int b = 0; b <= 1111; b++) {
int c = a + b;
if (fun(a) + fun(b) + fun(c) == num) {
cout << a << " + " << b << " = " << c << endl;
}
}
}
return 0;
}
int fun(int x) {
int numx = 0;
int n[10] = {6, 2, 5, 5, 4, 5, 6, 3, 7, 6}; //表示 0 ~ 9 需要的火柴數
while (x / 10 != 0) { //統計表示低位所需的火柴總數
numx += n[x%10];
x = x / 10;
}
numx += n[x];
return numx;
}
運行結果:
數的全排列
123 的全排列是 123、132、213、231、312、321
Question:輸入一個數 n,求 123…n 這個數 的全排列 (n<9)
求 123 的全排列
#include<iostream>
using namespace std;
int main() {
int a, b, c;
for (a = 1; a <= 3; a++) {
for (b = 1; b <= 3; b++) {
for (c = 1; c <= 3; c++) {
if (a != b && a != c && b != c) {
cout << a << b << c << " ";
}
}
}
}
return 0;
}
求 123456789 的全排列到見下章-萬能的搜索
End.