一、连续子数组最大和问题
#include <iostream>
#include <assert.h>
using namespace std;
int MaxSumArray(const int *arr, const unsigned int len, unsigned int *start, unsigned int *end)
{
assert(NULL != arr && len > 0 && NULL != start && NULL != end);
//array to store each sum of array ended by index
int *maxArray = new int[len];
//max sum of array
int max = 0;
maxArray[0] = arr[0];
max = maxArray[0];
*start = 0;
*end = 0;
for(unsigned int i = 1; i < len; ++i){
if(maxArray[i - 1] > 0){
maxArray[i] = maxArray[i - 1] + arr[i];
}else{
maxArray[i] = arr[i];
*start = i;
}
if(maxArray[i] > max){
max = maxArray[i];
*end = i;
}
}
delete [] maxArray;
return max;
}
int main(int argc, char **argv)
{
int array[] = {1,-2,3,10,-4,7,2,-5};
unsigned int start, end;
int value = MaxSumArray(array, sizeof(array) / sizeof(array[0]), &start, &end);
cout << "max sum " << value << " start index " << start << " end index " << end << endl;
return 0;
}
二、数塔问题
#include <iostream>
#include <assert.h>
using namespace std;
void display(const unsigned int (*arr)[5], const unsigned int N)
{
cout << "array display" << endl;
for(unsigned int i = 0; i < N; ++i){
for(unsigned int j = 0; j < 5; ++j){
cout << arr[i][j] << '\t';
}
cout << endl;
}
}
unsigned int NumberTowel(unsigned int (*arr)[5], const unsigned int N)
{
assert(NULL != arr && N > 0);
for(unsigned int i = N - 1; i > 0; --i){
for(unsigned int j = 0; j < i; ++j){
arr[i - 1][j] += arr[i][j] > arr[i][j + 1] ? arr[i][j] : arr[i][j + 1];
}
//display(arr, N);
}
return arr[0][0];
}
int main(int argc,char **argv)
{
unsigned int data[5][5] = {
{ 9, 0, 0, 0, 0},
{12,15, 0, 0, 0},
{10, 6, 8, 0, 0},
{ 2,18, 9, 5, 0},
{19, 7,10, 4,16}
};
cout << "max value " << NumberTowel(data, 5) << endl;
return 0;
}
三、背包问题
#include <iostream>
#define W 10
using namespace std;
#if 0
//max has been defined in file iostream
template<class T>
inline T max(const T value1, const T value2)
{
return value1 > value2 ? value1 : value2;
}
#endif
unsigned int MaxValue(const unsigned int *weight, const unsigned int *value, const unsigned int N)
{
unsigned int (*table)[W + 1] = new unsigned int[N][W + 1];
for(unsigned int i = 0; i < N; ++i){
table[i][0] = 0;
}
for(unsigned int i = 0; i < W; ++i){
table[0][i] = 0;
}
for(unsigned int i = 1; i < N; ++i){
for(unsigned int j = 1; j <= W; ++j){
if(weight[i] > j){
table[i][j] = table[i - 1][j];
}else{
table[i][j] = max(table[i - 1][j], table[i - 1][j - weight[i]] + value[i]);
}
}
}
unsigned int ret = table[N - 1][W];
delete [] table;
return ret;
}
int main(int argc,char * * argv)
{
unsigned int weight[6] = {2, 3, 1, 4, 6, 5};
unsigned int value[6] = {5, 6, 5, 1, 19, 7};
cout << "max value " << MaxValue(weight, value, 6) << endl;
}