Basic ideas and typical examples of greedy algorithm

Source: Internet
Author: User
Tags arithmetic value of pi

Greedy algorithm

First, the algorithm thought

The basic idea of greedy method:
--gradually approaching a given target from an initial solution of the problem to obtain a better solution as quickly as possible. The algorithm stops when a step in an algorithm can no longer move forward.
There are problems with this algorithm:
1. The final solution to be obtained is not guaranteed to be optimal;
2. Can not be used to find the maximum or minimum solution problem;
3. Only the range of feasible solutions satisfying certain constraints can be obtained.


The process of implementing the algorithm:
Starting from an initial solution of a problem;
While you can move forward one step toward a given total target
Finding a solution element of a feasible solution;
A feasible solution to the problem of the combination of all solution elements;

Second, analysis of examples

1, [knapsack problem] has a backpack, backpack capacity is m=150. There are 7 items that can be divided into any size.
It is required to maximize the total value of the items loaded into the backpack, but not to exceed the total capacity.

Item A B C D E F G
Weight 35 30 60 50 40 10 25
Value 10 40 30 50 35 40 30


Analysis:

Objective function: ∑pi max
The restriction is that the total weight of the loaded item does not exceed the backpack capacity: ∑wi<=m (m=150)


(1) According to the greedy strategy, each time to select the most valuable items loaded into the backpack, the results are optimal?
(2) Can the optimal solution be obtained by loading the items with the smallest space for each selection?
(3) Each time the unit capacity value of the most valuable items, become the solution of the strategy.

Http://baike.baidu.com/view/298415.htm

The realization of this algorithm is the learning algorithm analysis and design of this course needs.

The greedy algorithm is the first type of algorithm to be contacted. The algorithm is simple and fast from the local optimal. For one problem the most

The greedy method is a better algorithm to find the suboptimal solution when the optimal solution can only be obtained by the method of poor lifting.

Greedy method is a kind of improved hierarchical processing method. The characteristic of design algorithm by greedy method is to proceed step by step, according to a

The optimization measure (either the objective function or the target function) is guaranteed to obtain the local optimal solution at each step. Every

Step only consider one data, its selection should satisfy the local optimization condition. If the next data is connected with some of the optimal solutions, it is no longer possible

The data is not added to the partial solution until all the data is enumerated or can no longer be added. This can

It is called the greedy method to get the optimal solution in some measure.

The key problem of using greedy method is to choose the optimal measure which can produce the optimal solution of the problem.

Suppose there are n objects and a backpack, the object I has a quality WI, the value is pi, and the load capacity of the backpack is M. If the object I is

Part XI (1<=i<=n,0<=xi<=1) is loaded into the backpack, then there is a value of pi*xi. In the constraint condition

(W1*X1+W2*X2+............+WN*XN) <=m the goal (P1*X1+P2*X2+......+PN*XN) to a great

0<=xi<=1,pi>0,1<=i<=n. This problem is called knapsack problem (knapsack problem).

To get the optimal solution, we need to find a balance between benefit growth and backpack capacity consumption. In other words, you should always put that

Some of the most effective objects are put into the backpack first.

In the program of implementing the algorithm, the core program of implementing the algorithm has not encountered a great problem, but the realization of finding the best measure standard

The program is constantly in trouble!

When looking for the optimal metric, the approximate direction is to use the bubble sort algorithm. That is, according to P[i]/w[i] to the size of w[i]

Sort.

When using this algorithm directly, you can have the following code:

According to the benefit Temparray[i] The order of the weight w[i], prepare for entering 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//with similar bubble sorting algorithm, according to benefit P[i]/w[i] to w[i] Sort

7 for (i = 0; i < n; i++)

8 {

9 float swapmemory = 0;

-Float temp;

11

temp = Temparray[i];

index = i;

14

(j = i + 1; j < N; j + +)

16 {

if (temp < temparray[j])

18 {

temp = Temparray[j];

index = j;

21}

22}

23

24//To W[i] sort

Swapmemory = W[index];

W[index] = W[i];

W[i] = swapmemory;

28}

29

return;

31}

However, after careful analysis of the algorithm can be found that the "take doctrine" is not used here!

The test case for the algorithm is p[3] = {10, 15};w[3] = {18, 15,}. The results are 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

Can see its benefit is x[3] = {1.4, 1.6, 1.5}, so in the case of M = 20, its expected output is

0,1,0.5. But is it actually the case?

When the program enters this function after the necessary variables are initialized, it enters the perimeter loop, which is the 7th line of the program. The first round of follow-up

Ring, temp = temparray[0] = 1.4,index = i = 0; The program runs to line 15th, that is, into the inner loop.

The main task of the inner loop is to find a maximum benefit from the first and 1 elements and save the subscript at this point. After the 24th line,

, you begin to sort w[i].

Here's the problem! The sorted w[i] = {1.6, 1.6, 1.5}, so the w[i] was ordered to change the original of W[i]

In order, also changed the original value of W[i]!

Accordingly, some modifications have been made to get the following piece of 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 initial value to map array 0

7 {

8 Sortresult[i] = 0;

9}

10

one for (i = 0; i < n; i++)

12 {

float swapmemory = 0;

float temp;

15

temp = Temparray[i];

index = i;

18

for (j = i; J < N; j + +)

20 {

if ((Temp < temparray[j]) && (sortresult[j] = = 0))

22 {

temp = Temparray[j];

index = j;

25}

26}

27

if (sortresult[index] = = 0)

29 {

Sortresult[index] = ++k;

31}

32}

33

(i = 0; i < n; i++)

35 {

if (sortresult[i] = = 0)

37 {

Sortresult[i] = ++k;

39}

40}

41

return;

43}

One of the biggest changes since the modification was not to continue to sort directly on w[i], but instead to use a map array of w[i]

Sortresult[i]. Sortresult[i] The value of the element in the store is calculated according to the benefit of w[i] size order! So W[i] Original

The value and position have not changed, so that the algorithm can be implemented!

As for there is no better version of the implementation, still in the exploration!

#include <stdio.h>

#define MAXSIZE 100//assumed total number of objects

#define M 20//Backpack load capacity

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 output results

{

X[i] = 0;

}

for (i = 0; i < n; i++)

{

temp = sortresult[i];//The order in which the objects are taken

if (W[temp] > Cu)

{

Break

}

X[temp] = 1;//removed if appropriate

Cu-= w[temp];//changes the capacity accordingly

}

if (i <= N)//Make backpack full

{

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 initial value to map array 0

{

Sortresult[i] = 0;

}

for (i = 0; i < n; i++)

{

float temp = temparray[i];

index = i;

Find the maximum benefit and save the subscript at this time

for (j = 0; J < N; j + +)

{

if ((Temp < temparray[j]) && (sortresult[j] = = 0))

{

temp = Temparray[j];

index = j;

}

}

Sort the w[i] as a marker

if (sortresult[index] = = 0)

{

Sortresult[index] = ++k;

}

}

Modify the least effective sortresult[i] tag

for (i = 0; i < n; i++)

{

if (sortresult[i] = = 0)

{

Sortresult[i] = ++k;

}

}

Return

}

Get all the 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" 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 ();

}

Basic idea of greedy algorithm and typical example (turn)

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.