Application of greedy algorithms in backpacks)

Source: Internet
Author: User
Implement this Algorithm Learning Algorithm analysis and design.
Greedy algorithms are the first type of algorithms. The algorithm is simple and fast based on local optimization. The most problematic
The optimal solution can only be obtained by the exhaustive method, and the greedy method is a better algorithm for finding the sub-optimal solution of the problem.
Greedy method is an improved hierarchical processing method. The greedy algorithm is designed step by step.
The optimization measure (either the target function or the target function) ensures that the local optimal solution can be obtained at each step. Each
Only one data is considered in step. Its selection should meet the local optimization conditions. If the next data is connected with some of the optimal solutions
When the row is parsed, the data is not added to the partial decomposition until all data is enumerated or cannot be added. This capability
The hierarchical processing method for obtaining the optimal solution in a certain measurement is called greedy.
Selecting the optimal measurement criteria that can generate the optimal solution is the core issue of using the greedy method.
Assume that there are n objects and a backpack, the object I has a mass WI, the value is pi, and the carrying capacity of the backpack is M. If
If part of Xi (1 <= I <= N, 0 <= xi <= 1) is loaded into the backpack, it is worth pI * Xi. Under Constraints
(W1 * X1 + W2 * X2 + ............ + Wn * XN) <= m to make the target (P1 * X1 + p2 * X2 + ...... + PN * XN ).
0 <= xi <= 1, PI> 0, 1 <= I <= n. This problem is called a backpack problem (knapsack problem ).
To get the optimal solution, we need to find a balance between the increase in efficiency and the consumption of backpack capacity. That is to say, we should always
Some objects with the highest benefits are first placed in a backpack.
When the algorithm is implemented Program However, the core program implementing the algorithm has not encountered many problems.
The program is always in trouble!
When looking for the Optimal measurement criteria, the general direction is to use the Bubble Sorting Algorithm. That is, according to the size of P [I]/W [I ],
Sort.
When using this algorithm directly, you can use the following section: Code :
// Sort weight W [I] by benefit temparray [I] to prepare for the greedy algorithm
1 void sort (float temparray [], flaot W [], int N)
2 {
3 int I = 0, j = 0;
4 int Index = 0;
5
6 // sort by P [I]/W [I] To W [I] using a bubble-like Sorting Algorithm
7 For (I = 0; I <n; I ++)
8 {
9 float swapmemory = 0;
10 float temp;
11
12 temp = temparray [I];
13 Index = I;
14
15 For (j = I + 1; j <n; j ++)
16 {
17 if (temp <temparray [J])
18 {
19 temp = temparray [J];
20 Index = J;
21}
22}
23
24 // sort W [I]
25 swapmemory = W [Index];
26 W [Index] = W [I];
27 W [I] = swapmemory;
28}
29
30 return;
31}
However, after careful analysis of the algorithm, we can find that "tailism" cannot be used here!
The algorithm test case is P [3] = {25, 24, 15}; W [3] = {18, 15, 10 }. The result is as follows:
Please input the total count of object: 3
Please input array of P:
25 24 15
Now please input array of W:
18 15 10

Sortresult [I] is:
1-107374176.000000, 1 1.600000, 2 1.600000

After arithmetic data: X [I]
0.000000 0.333333 0.000000

We can see that the benefit is X [3] = {1.4, 1.6, 1.5}. So when M = 20, the expected output result is
0, 1, and 0.5. But is that true?
When the program enters this function after necessary variable initialization, it enters the peripheral loop, that is, the program's 7th rows. First round
In the loop, temp = temparray [0] = 1.4, Index = I = 0; the program runs to 15th rows, that is, it enters the inner loop.
The main task of the inner loop is to find a maximum benefit from the I + 1 element and save the subscript at this time. After 24th rows
To sort the W [I.
The problem is here! After sorting, W [I] = {1.6, 1.6, 1.5}. Therefore, after sorting W [I], the original value of W [I] is changed.
In order, the original value of W [I] is changed!

Then, make some modifications and get the following code:
1 void sort (float temparray [], int sortresult [], int N)
2 {
3 int I = 0, j = 0;
4 int Index = 0, K = 0;
5
6 For (I = 0; I <n; I ++) // assign the initial value 0 to the ing Array
7 {
8 sortresult [I] = 0;
9}
10
11 For (I = 0; I <n; I ++)
12 {
13 float swapmemory = 0;
14 float temp;
15
16 temp = temparray [I];
17 Index = I;
18
19 For (j = I; j <n; j ++)
20 {
21 if (temp <temparray [J]) & (sortresult [J] = 0 ))
22 {
23 temp = temparray [J];
24 Index = J;
25}
26}
27
28 If (sortresult [Index] = 0)
29 {
30 sortresult [Index] = ++ K;
31}
32}
33
34 For (I = 0; I <n; I ++)
35 {
36 IF (sortresult [I] = 0)
37 {
38 sortresult [I] = ++ K;
39}
40}
41
42 return;
43}
The biggest change after modification is that the direct sorting of W [I] is not continued, but a ing array of W [I] is used.
Sortresult [I]. The element values in sortresult [I] are stored in the order of W [I] size calculated based on the benefit! In this way, W [I] is old.
So that the algorithm can be implemented!
Is there any better implementation version? You are still exploring it!

# Include <stdio. h>
# Define maxsize 100 // assume the total number of objects
# Define M 20 // carrying capacity of the backpack

// Algorithm core, Greedy Algorithm
Void greedy (float W [], float X [], int sortresult [], int N)
{
Float Cu = m;
Int I = 0;
Int temp = 0;

For (I = 0; I <n; I ++) // prepare the output result.
{
X [I] = 0;
}

For (I = 0; I <n; I ++)
{
Temp = sortresult [I]; // obtain the object order.
If (W [temp]> Cu)
{
Break;
}

X [temp] = 1; // retrieve if appropriate
Cu-= W [temp]; // change the capacity accordingly.
}

If (I <= N) // fill the backpack
{
X [temp] = Cu/W [temp];
}

Return;
}

Void sort (float temparray [], int sortresult [], int N)
{
Int I = 0, j = 0;
Int Index = 0, K = 0;

For (I = 0; I <n; I ++) // assign an initial value 0 to the ing Array
{
Sortresult [I] = 0;
}

For (I = 0; I <n; I ++)
{
Float temp = temparray [I];

Index = I;

// find the greatest benefit and save the subscript
for (j = 0; j {< br> If (temp {< br> temp = temparray [J];
Index = J;
}< BR >}

// Mark and sort W [I]
If (sortresult [Index] = 0)
{
Sortresult [Index] = ++ K;
}
}

// Modify the sortresult [I] tag with the lowest benefit
For (I = 0; I <n; I ++)
{
If (sortresult [I] = 0)
{
Sortresult [I] = ++ K;
}
}

Return;
}

// Obtain all input information of this algorithm
Void getdata (float P [], float W [], int * n)
{
Int I = 0;

Printf ("Please input the total count of object :");
Scanf ("% d", N );

Printf ("Please input array of P: \ n ");
For (I = 0; I <(* n); I ++)
{
Scanf ("% F", & P [I]);
}

Printf ("Now please input array of W: \ n ");
For (I = 0; I <(* n); I ++)
{
Scanf ("% F", & W [I]);
}

Return;
}

Void output (float X [], int N)
{
Int I;

Printf ("\ n \ nafter arithmetic data: advise Method \ n ");
For (I = 0; I <n; I ++)
{
Printf ("X [% d] \ t", I );
}

Printf ("\ n ");
For (I = 0; I <n; I ++)
{
Printf ("% 2.3f \ t", X [I]);
}

Return;
}

Void main ()
{
Float P [maxsize], W [maxsize], X [maxsize];
Int I = 0, n = 0;
Int sortresult [maxsize];

Getdata (p, W, & N );

For (I = 0; I <n; I ++)
{
X [I] = P [I]/W [I];
}

Sort (x, sortresult, N );

Greedy (w, x, sortresult, N );

Output (x, N );

Getch ();
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.