Book Image

C++ Data Structures and Algorithm Design Principles

By : John Carey, Anil Achary, Shreyans Doshi, Payas Rajan
Book Image

C++ Data Structures and Algorithm Design Principles

By: John Carey, Anil Achary, Shreyans Doshi, Payas Rajan

Overview of this book

C++ is a mature multi-paradigm programming language that enables you to write high-level code with a high degree of control over the hardware. Today, significant parts of software infrastructure, including databases, browsers, multimedia frameworks, and GUI toolkits, are written in C++. This book starts by introducing C++ data structures and how to store data using linked lists, arrays, stacks, and queues. In later chapters, the book explains the basic algorithm design paradigms, such as the greedy approach and the divide-and-conquer approach, which are used to solve a large variety of computational problems. Finally, you will learn the advanced technique of dynamic programming to develop optimized implementations of several algorithms discussed in the book. By the end of this book, you will have learned how to implement standard data structures and algorithms in efficient and scalable C++ 14 code.
Table of Contents (11 chapters)

The Knapsack Problem

Now, let's reconsider the knapsack problem we looked at in Chapter 5, Greedy Algorithms, which we could describe as the subset sum problem's "big brother." It asks the following:

"Given a knapsack of limited capacity and a collection of weighted items of different values, what set of items can be contained within the knapsack that produces the greatest combined value without exceeding the capacity?"

This problem is also a characteristic example of NP-completeness, and as such, it shares many close ties to the other problems in this class.

Consider the following example:

Capacity —> 10 

Number of items —> 5

Weights —> { 2, 3, 1, 4, 6 } 

Values —>  { 4, 2, 7, 3, 9 }

With this data, we can produce the following subsets:

Figure 9.2: All possible subsets for the given 0-1 knapsack problem
Figure 9.2: All possible subsets for the given...