Common algorithm design method (6)-greedy method

Source: Internet
Author: User

The greedy method is a method that does not pursue the optimal solution and only wants to obtain a satisfactory solution. The greedy method can quickly get a satisfactory solution, because it saves a lot of time to find the optimal solution to exhaust all possibilities. The greedy method is usually based on the current situation for optimal selection, regardless of the overall situation of various possibilities, so the greedy method should not backtrack.
For example, when purchasing and looking for money, in order to minimize the number of coins to be recovered, we do not consider all kinds of publishing schemes for finding the change, but start from the currency with the largest face value, consider each currency in a descending order. First, try to use a currency with a large nominal value. When the amount of a currency with a large nominal value is insufficient, consider the next currency with a smaller nominal value. This is the use of the greedy method. This method is always optimal here because Bank Clever arrangement of coin categories and coin denominations. For example, only coins with a nominal value of 1, 5, and 11 are expected to be recovered. According to the greedy algorithm, we should find one coin with 11 nominal values and four coins with one nominal value, and retrieve five coins in total. However, the optimal solution should be 3 Coins with 5 nominal values.
[Problem] Packing Problem
Problem description: The packing problem is described as follows: 0, 1 ,... N types of n-1 items, volume: v0, V1 ,... Vn-1. Pack the N items into several boxes with a capacity of v. It is agreed that the volume of these N items shall not exceed V, that is, for 0 ≤ I <n, there is 0 <VI ≤ v. The number of boxes required for different packing schemes may be different. The packing problem requires that the number of boxes containing the N items be less.
If we divide the set of N items into N or all subsets of N items, the optimal solution can be found. However, the total number of all possible partitions is too large. For an appropriately large N, it is unacceptable to find out all possible classifications. Therefore, we adopt a very simple Approximation Algorithm for the packing problem, that is, the greedy method. This algorithm puts items in the first box that can be placed in sequence. Although this algorithm cannot find the optimal solution, it can still find a very good solution. Without interruption, the volume of N items is sorted in ascending order, that is, V0 is ≥v1 ≥... ≥ Vn-1. If the preceding requirements are not met, you only need to first sort the N items by their volume from large to small, and then re-number the items according to the sorting result. The packing algorithm is described as follows:
{Input box volume;
Number of input items N;
Input the volume of each item in the order of size from large to small;
The pre-used box chain is empty;
The pre-configured box counter box_count is 0;
For (I = 0; I <n; I ++)
{Search for the box J that can be placed in item I in sequence from the first box in use;
If (no more items can be placed in used boxes I)
{Use another box and put item I into it;
Box_count ++;
}
Else
Put item I into the box J;
}
}
The preceding algorithm can calculate the number of boxes box_count and find the items in each box. The following example shows that the algorithm may not be able to find the optimal solution. There are 6 items in size: 60, 45, 35, 20, 20, and 20, respectively, the box volume is 100 units. Based on the above algorithm, three boxes are required. The items in each box are: 1 and 3 in the first box; 2, 4, and 5 in the second box; the third box contains 6 items. The optimal solution is two boxes with items 1, 4, 5, 2, 3, and 6 respectively.
If the items in each box are represented by a linked list, the first node pointer of the linked list is stored in a structure, and the remaining space is recorded in the structure and the first pointer of the linked list of the items in the box. In addition, the information of all boxes is also a linked list. The following is a program written based on the above algorithms.
[Program]
# Include <stdio. h>
# Include <stdlib. h>
Typedef struct ele
{Int vno;
Struct ele * link;
} Ele;
Typedef struct hnode
{Int remainder;
Ele * head;
Struct hnode * next;
} Hnode;

Void main ()
{Int N, I, box_count, box_volume, *;
Hnode * box_h, * box_t, * J;
Ele * P, * q;
Printf ("input box volume/N ");
Scanf ("% d", & box_volume );
Printf ("number of input items/N ");
Scanf ("% d", & N );
A = (int *) malloc (sizeof (INT) * n );
Printf ("input the volume of each item in the order of size from large to small :");
For (I = 0; I <n; I ++) scanf ("% d", A + I );
Box_h = box_t = NULL;
Box_count = 0;
For (I = 0; I <n; I ++)
{P = (Ele *) malloc (sizeof (Ele ));
P-> vno = I;
For (j = box_h; J! = NULL; j = J-> next)
If (J-> remainder> =) Break;
If (j = NULL)
{J = (hnode *) malloc (sizeof (hnode ));
J-> remainder = box_volume-a;
J-> head = NULL;
If (box_h = NULL) box_h = box_t = J;
Else box_t = boix_t-> next = J;
J-> next = NULL;
Box_count ++;
}
Else J-> remainder-=;
For (q = J-> next; Q! = NULL & Q-> link! = NULL; q = Q-> link );
If (q = NULL)
{P-> link = J-> head;
J-> head = P;
}
Else
{P-> link = NULL;
Q-> link = P;
}
}
Printf ("% d boxes used in total", box_count );
Printf ("the situations where items are packed in different boxes are as follows :");
For (j = box_h, I = 1; J! = NULL; j = J-> next, I ++)
{Printf ("only boxes in % 2D, remaining volume % 4D, loaded items;/N", I, j-> remainder );
For (P = J-> head; P! = NULL; P = p-> link)
Printf ("% 4D", p-> vno + 1 );
Printf ("/N ");
}
}

[Problem] horse Traversal
Problem description: on the 8x8 checkerboard, start from any specified square to find a path for the horse to travel through every square and pass through only once.
The horse is in a certain square, and there can be at most 8 different positions in one step ,. For example, if the two-dimensional array Board [] [] is used to represent the Board, its elements record the step number when the horse passes through the position. Set an order for the eight possible steps (known as the method) of the horse. For example, if the current position is in the (I, j) Square of the chessboard, the next possible position is (I + 2, J + 1), (I + 1, J + 2), (I-1, J + 2), (I-2, J + 1), (I-2, J-1), (I-1, j-2), (I + 1, J-2), (I + 2, J-1), the actual locations that can be taken are limited to those that have not passed and do not cross the border. To facilitate program approval, you can introduce two arrays to store the vertical and horizontal increments of the current location by various possible steps.
4 3
5 2
Horse
6 1
7 0

For this question, we can generally adopt the Backtracking Method. Here we use the warnsdoff strategy to solve the problem. This is also a greedy method. The greedy criterion for choosing the next exit is in those permitted locations, select the least exit location. Such as the current position of the horse (I, j) Only three exits, they are the position (I + 2, J + 1), (I-2, J + 1) and (I-1, j-2), such as respectively to these locations, these three locations and respectively have different exits, assuming that the three locations of the number of exits respectively 4, 2, 3, then the program chooses to let the horse (I-2, J + 1) position.
Because the program adopts a greedy method, the entire process of finding and resolving is always forward without backtracking, so the solution can be found very quickly. However, there are actually solutions for some starting locations, and this algorithm cannot find the solutions. If the solution cannot be found, the program can find the solution by changing the selection sequence of the eight possible export ports. To change the exit selection order is to change the selection criteria for the same exit. The following Program introduces the variable start to control the selection sequence of eight possible methods. The start time is 0. When the solution cannot be found, add 1 to start and find the solution again. The following procedure is detailed.
[Program]
# Include <stdio. h>
Int delta_ I [] = {2, 1,-1,-2,-2,-1, 2 };
Int delta_j [] = {1, 2, 1,-1,-2,-2,-1 };
Int Board [8] [8];
Int exitn (int I, Int J, int S, int A [])
{Int I1, J1, K, count;
For (COUNT = k = 0; k <8; k ++)
{I1 = I + delta_ I [(S + k) % 8];
J1 = I + delta_j [(S + k) % 8];
If (I1> = 0 & I1 <8 & J1> = 0 & J1 <8 & Board [I1] [J1] = 0)
A [count ++] = (S + k) % 8;
}
Return count;
}

Int next (int I, Int J, int S)
{Int M, K, mm, Min, a [8], B [8], temp;
M = exitn (I, j, S, );
If (M = 0) Return-1;
For (min = 9, K = 0; k <m; k ++)
{Temp = exitn (I + delta_ I [A [k], J + delta_j [A [k], S, B );
If (temp <min)
{Min = temp;
Kk = A [k];
}
}
Return KK;
}

Void main ()
{Int Sx, Sy, I, J, step, no, start;
For (SX = 0; SX <8; SX ++)
For (SY = 0; Sy <8; Sy ++)
{Start = 0;
Do {
For (I = 0; I <8; I ++)
For (j = 0; j <8; j ++)
Board[J] = 0;
Board [SX] [sy] = 1;
I = SX; j = sy;
For (step = 2; Step <64; Step ++)
{If (NO = next (I, j, start) =-1) break;
I + = delta_ I [No];
J + = delta_j [No];
Board[J] = step;
}
If (Step> 64) break;
Start ++;
} While (Step <= 64)
For (I = 0; I <8; I ++)
{For (j = 0; j <8; j ++)
Printf ("% 4D", board[J]);
Printf ("/n ");
}
Scanf ("% * C ");
}
}

 

 

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.