生活随笔
收集整理的這篇文章主要介紹了
蓝桥杯2015决赛-方格填数-枚举 or dfs
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目描述
在2行5列的格子中填入1到10的數字。
要求:相鄰的格子中的數,右邊的大于左邊的,下邊的大于上邊的。
如下圖所示的2種,就是合格的填法。
請你計算一共有多少種可能的方案。
輸出
請輸出該整數,不要輸出任何多余的內容
法一:
代碼如下:
#include <iostream>
using namespace std
;
bool vis
[12];
int a
[12][12], ans
= 0;bool check(int x
, int y
) {if (x
== 0) {if (a
[x
][y
] > a
[x
][y
- 1] || y
== 0) {return true;}}if (a
[x
][y
] > a
[x
][y
- 1] && a
[x
][y
] > a
[x
- 1][y
] || y
== 0 && a
[x
][y
] > a
[x
- 1][y
])return true;return false;
}void dfs(int x
, int y
) {if (x
== 2)ans
++;for (int i
= 1; i
<= 10; i
++) {a
[x
][y
] = i
;if (!vis
[i
]) {if (check(x
, y
)) {vis
[i
] = true;if (y
== 4) {dfs(x
+ 1, 0);} else {dfs(x
, y
+ 1);}vis
[i
] = false;}}}
}int main() {dfs(0, 0);cout
<< ans
<< endl
;return 0;
}
法二:
代碼如下:
#include <iostream>
#include <algorithm>
using namespace std
;int a
[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int ans
;bool check() {if (a
[1] > a
[0] && a
[2] > a
[1] && a
[3] > a
[2] &&a
[4] > a
[3] && a
[6] > a
[5] && a
[7] > a
[6] &&a
[8] > a
[7] && a
[9] > a
[8] && a
[5] > a
[0] &&a
[6] > a
[1] && a
[7] > a
[2] && a
[8] > a
[3] &&a
[9] > a
[4]) {return true;}return false;
}int main() {do {if (check())ans
++;} while (next_permutation(a
, a
+ 10));cout
<< ans
<< endl
;return 0;
}
next_permutation()的錯誤使用導致錯誤
樣例代碼如下:
#include <iostream>
#include <algorithm>
using namespace std
;int a
[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int ans
;bool check() {if (a
[2] > a
[1] && a
[3] > a
[2] && a
[4] > a
[3] &&a
[5] > a
[4] && a
[7] > a
[6] && a
[8] > a
[7] &&a
[9] > a
[8] && a
[10] > a
[9] && a
[6] > a
[1] &&a
[7] > a
[2] && a
[8] > a
[3] && a
[9] > a
[10] &&a
[10] > a
[5]) {return true;}return false;
}int main() {do {if (check())ans
++;} while (next_permutation(a
, a
+ 10));cout
<< ans
<< endl
;return 0;
}
在這里可以刷一下同樣可以用next_permutation()函數AC的題目:
[藍橋杯2016初賽]方格填數
[藍橋杯2017初賽]紙牌三角形
總結
以上是生活随笔為你收集整理的蓝桥杯2015决赛-方格填数-枚举 or dfs的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。