回溯法

N皇后问题

 

递归:

#include
#include
#include
#include
#include
using namespace std;
typedef pair<int, int> P;
int n,sum;
vector

v; bool judge(int x, int y){ for (int i = 0; i < v.size(); i++){ float bioas = (v[i].second*1.0 - y*1.0) / (v[i].first*1.0 - x * 1.0); if (x == v[i].first || y == v[i].second || abs(bioas) == 1.0) return false; } return true; } void trace(int index){ if (index >= n){ sum++; for (int i = 0; i < v.size(); i++) printf("(%d, %d) ", v[i].first, v[i].second); cout << endl; return; } for (int i = 0; i < n; i++){ if (judge(index, i)){ v.push_back(P(index, i)); trace(index+1); v.erase(v.begin()+index, v.end()); } } } int main(){ while(cin >> n){ v.clear(); sum = 0; trace(0); cout << sum << endl; } return 0; }

View Code

迭代:

#include
#include
#include
#include
#include
using namespace std;
typedef pair<int, int> P;
int n,sum;
vector

v; bool judge(int x, int y){ for (int i = 0; i < v.size(); i++){ float bioas = (v[i].second*1.0 - y*1.0) / (v[i].first*1.0 - x * 1.0); if (x == v[i].first || y == v[i].second || abs(bioas) == 1.0) return false; } return true; } void trace(int index){ if (index >= n){ sum++; for (int i = 0; i < v.size(); i++) printf("(%d, %d) ", v[i].first, v[i].second); cout << endl; return; } for (int i = 0; i < n; i++){ if (judge(index, i)){ v.push_back(P(index, i)); trace(index+1); v.erase(v.begin()+index, v.end()); } } } int main(){ while(cin >> n){ v.clear(); sum = 0; trace(0); cout << sum << endl; } return 0; }

View Code

0-1背包问题

#include
#include
#include
#include
using namespace std;
typedef pair<int, int> P;
int n, maxV, W;
string maxS;
vector

v; bool cmp(P a, P b){ return a.first > b.first; } void solve(int index, int sumV, int sumW, int fV, string s){ if (maxV < sumV){ maxV = sumV; maxS = s; } if (index >= n || maxV >= fV + sumV) return; string left = s; solve(index+1, sumV, sumW, fV - v[index].first, left); if(sumW + v[index].second <= W && sumV + fV > maxV){ stringstream ss; ss << index+1; string right = s +' '+ ss.str(); solve(index+1, sumV + v[index].first, sumW + v[index].second, fV - v[index].first, right); } } int main(){ while(cin >> n >> W) { v.clear(); maxS.clear(); maxV = 0; int fV = 0; for (int i = 0; i < n; i++) { int x, w; cin >> x >> w; fV += x; v.push_back(P(x,w)); } //sort(v.begin(), v.end(),cmp); string s="最佳解为:"; solve(0, 0, 0, fV ,s); cout << maxV << endl; cout << maxS << endl; } return 0; } /* 4 10 42 7 25 5 12 3 40 4 65 */

View Code

 

你可能感兴趣的:(回溯法)