算法竞赛入门经典 排列
生活随笔
收集整理的這篇文章主要介紹了
算法竞赛入门经典 排列
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目描述
習題2-6 排列(permutation)
用1,2,3…9,組成3個三位數abc,def和ghi,每個數字恰好使用一次,要求abc:def:ghi=1:2:3。按照“abc def ghi”的格式輸出所有解,每行一個解。提示:不必太動腦筋。
思路
全排列,在排列的過程中判斷這個數是否合理
具體代碼
#include <iostream>using namespace std;int path[10]; bool st[10];int merge(int l, int r) {int res = 0;for (int i = l; i <= r; i ++ )res = res * 10 + path[i];return res; }void dfs(int u) {if (u == 9 + 1) {int a = merge(1, 3);int b = merge(4, 6);int c = merge(7, 9);if (b == 2 * a && c == 3 * a) printf("%d %d %d\n", a, b, c);}for (int i = 1; i <= 9; i ++ )if (!st[i]) {path[u] = i;st[i] = true;dfs(u + 1);st[i] = false;} }int main() {dfs(1);return 0; }總結
以上是生活随笔為你收集整理的算法竞赛入门经典 排列的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 解决:pip警告!DEPRECATION
- 下一篇: python中的tkinter模块