#include <iostream> using namespace std; bool Kanpsack(int kanpsack_weight, int object_weight[], int object_num) { cout << kanpsack_weight << " " << *object_weight << " " << object_num << endl; if (kanpsack_weight == *object_weight) { return true; } else if (kanpsack_weight < *object_weight) { if (object_num == 1) { return false; } Kanpsack(kanpsack_weight, object_weight+1, object_num-1); return false; } else { if (object_num == 1) { return false; } Kanpsack(kanpsack_weight - *object_weight, object_weight+1, object_num-1); return true; } } bool Kanpsack_Nonrecursive(int kanpsack_weight, int object_weight[], int object_num) { int weight = kanpsack_weight; //int old_weight = weight; int num = object_num; int* object = object_weight; while (1) { if (weight == *object) { cout << weight << " " << *object << " " << num << endl; return true; } else if (weight < *object) { cout << weight << " " << *object << " " << num << endl; //weight = old_weight; num--; object++; } else { cout << weight << " " << *object << " " << num << endl; //old_weight = weight; weight = weight - *object; num--; object++; } if (num == 0) { return false; } } } void main() { int kanpsack_weight; cout << "Enter the weight accommodate by the knapsack : " << endl; cin >> kanpsack_weight; int object_num; cout << "Enter the number of the objects" << endl; cin >> object_num; int *object_weight = new int[object_num]; cout << "Enter the weight of objects (decreasing)" << endl; for (int i = 0; i < object_num; i++) { cin >> object_weight[i]; } if (Kanpsack(kanpsack_weight, object_weight, object_num)) { cout << "Succeed" << endl; } if (Kanpsack_Nonrecursive(kanpsack_weight, object_weight, object_num)) { cout << "Succeed" << endl; } delete[] object_weight; }