思路:这道题还是用了小小的剪枝,这里要注意的是该题有很多中构建树的顺序,但是,在这众多顺序中不一定都能保证输出的方案字典序最小。
构建搜索树:如图构建
剪枝,emmm,看代码:
#include<iostream> using namespace std; int a[20][30]; int b[30], an[30], mm[20], gg[20]; int n, m, mins=1000, kk; bool f(){ for (int i = 1; i <= m;++i) if (b[i] > an[i])return 0; return 1; } void add_of_s(int s, int y){ for (int i = 1; i <= m; ++i) an[i] = an[i] + y*a[s][i]; } void dfs(int s, int k){ if (k > n){ return; } if (kk >= mins){ return; } //剪枝 if (f()){ mins = kk; for (int i = 1; i <= mins; ++i)gg[i] = mm[i]; } for (int i = s+1; i <= n;++i) { kk++; mm[kk] = i; add_of_s(i, 1); dfs(i , k + 1); mm[kk] = 0; kk--; add_of_s(i, -1); } } int main(){ cin >> m; for (int i = 1; i <= m; ++i)cin >> b[i]; cin >> n; for (int i = 1; i <= n;++i) for (int j = 1; j <= m; ++j) cin >> a[i][j]; dfs(0, 0); cout << mins << " "; for (int i = 1; i <= mins; ++i) cout << gg[i] << " \n"[i == mins]; }
原文地址:https://www.cnblogs.com/ALINGMAOMAO/p/10662112.html
时间: 2024-10-29 08:59:51