Knapsack-Dynamic Programming

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>

using namespace std;

typedef struct
{
    int v;
    int w;
} Item;


int Knapsack(vector<Item> &items, int size, int numItems)
{
	int** A = new int*[numItems+1];
    for(int i=0;i<numItems+1; i++)
        A[i] = new int[size+1];
    // -------- Initial ------
    for(int j=0; j<size+1; j++)
        A[0][j] = 0;
	/* for(int i=0; i<numItems+1; i++)
	A[i][0] = 0;*/
    //
	int prew;
    for(int i=1; i<numItems+1; i++)
        for(int j=0; j<size+1; j++)
		{
			A[i][j] = max(A[i-1][j], j-items[i-1].w>=0?A[i-1][j-items[i-1].w]+items[i-1].v:0);
		}

	int v = A[numItems][size];
	delete []A;
    return v;
}

int main()
{
    ifstream infile;
    infile.open("knapsack_big.txt", ifstream::binary);

    // ---------------------
    string line;
    stringstream ss;
    getline(infile, line);
    ss << line;

    int knapsack_size;
    int item_num;
    ss >> knapsack_size >> item_num;
    // -------- Initialize ---------
    vector<Item> items(item_num);
	int ttt;
	int tt;
    for(int i=0; i<item_num; i++)
    {
		ss.clear();
		line.clear(); 
        getline(infile, line);
        ss << line;
		
		ss >> items[i].v;
		ss >> items[i].w;     
    }
    infile.close();
    // -------------------------
    
    int v = Knapsack(items, knapsack_size, item_num);
    cout << v << endl;
    return 0;

}


利用在计算A的矩阵时,交换顺序和只利用两行信息的特点,可以只需要2*size的内存空间即可:


#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <algorithm>

using namespace std;

typedef struct
{
    int v;
    int w;
} Item;


int FastKnapsack(vector<Item> &items, int size, int numItems)
{
	// ---- Initial -----------
	int ** A = new int*[2];
	for (int i=0; i<2; i++)
		A[i] = new int[size+1];

	for (int j=0; j<size+1; j++)
		A[0][j] = 0;

	// -----------------------
	for (int i=1; i<numItems+1; i++)
	{
		if (1 == i%2)
		{
			for (int j=1; j<size+1; j++)
			{
				A[1][j] = max(A[0][j], j-items[i-1].w>=0?A[0][j-items[i-1].w]+items[i-1].v:0);
			}
			
		}else
		{
			for (int j=1; j<size+1; j++)
			{
				A[0][j] = max(A[1][j], j-items[i-1].w>=0?A[1][j-items[i-1].w]+items[i-1].v:0);
			}
		}
	}

	int v = max(A[0][size], A[1][size]);
	delete []A;
    return v;
}



int main()
{
    ifstream infile;
    infile.open("knapsack_big.txt", ifstream::binary);

    // ---------------------
    string line;
    stringstream ss;
    getline(infile, line);
    ss << line;

    int knapsack_size;
    int item_num;
    ss >> knapsack_size >> item_num;
    // -------- Initialize ---------
    vector<Item> items(item_num);
    for(int i=0; i<item_num; i++)
    {
		ss.clear();
		line.clear(); 
        getline(infile, line);
        ss << line;
		
		ss >> items[i].v;
		ss >> items[i].w;     
    }
    infile.close();
    // -------------------------
    int v = FastKnapsack(items, knapsack_size, item_num);
	

    cout << v << endl;
    return 0;

}


你可能感兴趣的:(Knapsack-Dynamic Programming)