Summary of greedy algorithm

Source: Internet
Author: User

                                       贪心算法总结

First, the algorithm thought
The basic idea of greedy method:
From one of the initial solutions of the problem, the target is approached gradually, and the better solution can be obtained as soon 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 scope of feasible solutions satisfying certain constraints can be obtained.
The process of implementing the algorithm:
Starting from an initial solution of a problem;
While being able to move one step towards 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, the Problem of ACM
This topic, learning the greedy algorithm, the 18 questions given by the only 14 of the AC (the same two questions). Except for a few water problems. Most of the problem is to use the greedy algorithm to solve, do this set of problems, although the feeling is very difficult, but think of ways or can ac a few questions, did these topics make me on the greedy algorithm impression deepened, did not feel so abstract, is a progress it, but still not skilled, but also need to strengthen training.

The short cut says. Still in review recall, about the classic problem of greedy algorithm.

Classification and analysis of typical examples

"Knapsack problem"

Given a backpack carrying a weight of M. Consider n items, the weight of the item I, the value of WI (1≤i≤n), required to fill the backpack, and the items in the backpack the most value.
There are two types of knapsack problems (depending on whether the item can be cut). Suppose the item cannot be cut, called the 0-1 knapsack problem (Dynamic planning). If the item can be cut, it is called knapsack problem (greedy algorithm).

There are 3 ways to select items:
(1) As a 0-1 knapsack problem. The optimal value of 220 is obtained by using dynamic programming algorithm.
(2) as a 0-1 knapsack problem. Using greedy algorithms. Select items according to the order of price, get the best value 160.

Because items are not cut. The rest of the space is wasted.
(3) as a knapsack problem. Using greedy algorithms. Select items according to the order of price, get the best value 240.

Because the items can be cut, the rest of the space is loaded into part 3 of the item. and get better performance.

struct bag{    int w;          //物品的重量    int v;          //物品的价值    double c;       //性价比}a[1001];           //存放物品的数组
 sort factor (descending by Price/performance): BOOL CMP (bag a , bag b) {return  a . C >= B.c}  
//shape n is the number of items, C is the capacity m of the backpack, Array A is sorted by item's price/performance ratio in descending order  double  knapsack (int  N,        Bag a[], double  c) {double  cleft = c;  //Backpack's remaining capacity   int  i = 0 ;          double  b = 0 ;  //gain value   //when the backpack can also be fully loaded items I  while   (I<n && A[i].w<cleft)    {cleft-= A[I].W;    b + = A[I].V;  i++; } //full backpack of the remaining space  if  (i<n) b + = 1.0  *a[i].v*cleft/a[i].w; return  b;}  
假设要获得解向量,则须要在数据结构中增加物品编号:struct bag{    int w;    int v;    double x;       //装入背包的量。0≤x≤1    int index;      //物品编号    double c;}a[1001];
Double knapsack (int n, baga[], double c) {Double cleft = c;int i =0;Double b =0;     while(I<n &&a[I].w<=cleft) {Cleft-=a[I].W;B + =a[I].V;The original serial number of the item isa[I].index, all packed in backpacksa[a[i].index].x =1.0;i++;}if(i<n) {a[a[i].index].x =1.0*cleft/a[I].W;B + =a[a[i].index].x*a[I].V;}returnB;}

"Find the change."

Description of the problem:
The current face value is 2.5 cents, 1 angle respectively. 5 points, 1 cents, please give the best solution for n cents (the minimum number of coins required to find)
Problem Analysis:
According to common sense, we go to the store to buy things for money. The boss always gives us the maximum value first, if not enough to find the face value smaller, until the full. Suppose the boss is looking for a score or a few corners for you. Then you must not do it. In addition, he may not have so many bits and pieces of money for you to find. In fact, this is a typical problem of greedy choice.


Algorithm design and implementation of the problem:
Give me a sample first. If the boss wants to give me 99 cents, he has the above face value of 25,10,5. 1 of the number of coins, in order to find me the minimum number of coins, then he should be looking for it. Let's see how many 25 points we should find. 99/25=3. It looks like 3, if 4, we have to give the boss a 1 point. I'm not doing it. So the boss can only give me 3 25 points, because still give me 24, so I have to give 2 10 and 4 1 points.


Detailed implementation of pseudo-code

//找零钱算法 //By falcon //输入:数组m,依次存放从大到小排列的面值数。n为须要找的钱数,单位所有为分 //输出:数组num,对比数组m中的面值存放不同面值的硬币的个数。即找钱方案比方要找N分钱。先拿N除最大零钱面值,能够取模得出余数。 当然取整就是所找的最大面值零钱的个数。 所得余数再次处理,用的是一个循环结构。 N输入取值 M是定义的面值M[0]是最大面值 K是一个数组,存储各面值零钱的个数 i=0dowhile (N>0) K[0]=int(N/M[i]) N=moddo

"Fishing Problem"

Description of the problem:
John had H (1≤h≤16) hours, and there were N (2≤n≤25) lakes in the area, which were located just on one route, which was unidirectional. John departs from Lake 1 and can finish fishing at any lake.

But he can only get from a lake and there is a lake adjacent to it, and does not have to stop every lake.


Suppose the lake I (I=1~n-1), in 5 minutes, from Lake I to Lake I+1 required time with TI (0 Known in the first 5 minutes. Lake I estimates the number of catches to the fish for Fi (fi≥0). After every 5 minutes, it is estimated that the number of fish caught will be reduced by a constant Di (di≥0).

Suppose that the number of fish caught in a certain period is less than or equal to Di, then no fish will be caught in the next period. For simplicity's sake, suppose no other angler affects John's number of anglers.
Code to help John make plans for fishing trips so as to catch as many fish as possible.
Problem Request:
Input
For each set of test cases. The first line is N, and the next line is H. The following line is N integer fi (1≤i≤n). Then there is a row of n integers di (1≤i≤n), and the last line is N-1 integer ti (1≤i≤n-1).
Input
For each set of test cases. The first line is N, and the next line is H. The following line is N integer fi (1≤i≤n). Then there is a row of n integers di (1≤i≤n). The last line is a n-1 integer ti (1≤i≤n-1).


For each test case, output the time spent on each lake. This is John's plan to achieve the most fish to catch (the entire plan must be output on the same line). The next line is the number of fish caught.

(Suppose there are very many scenarios.) Choose as much time as you can for fishing at Lake 1. Even if the fish is not caught at some time, if it is not possible to differentiate, choose the time spent on Lake 2 fishing, and so on. )
Problem Analysis:
1) Data structure
Each lake estimates the number of fish to be fished, defined as an array: #define NUM 30
int F[num];
Each lake is estimated to be a descending value of the number of fish caught, defined as an array:
int D[num];
Travel time between adjacent lakes, defined as an array:
int T[num];
Fishing plan, defined as an array:
int Plan[num];
The number of lakes N, used for fishing time H, as much as the number of fishing best.
2) Enumerate the best fishing plans at the end of a free lake fishing trip
First, the time used for fishing is H, converted from hours to 5 minutes: H=HX60/5;
In this way, the time to fish for 5 minutes is called fishing once. Because John departs from Lake 1. Can end fishing at any lake, to get the best solution, you need to search.
3) Adopt the greedy strategy, each time choose the fish most lake fishing once
For every lake, this strategy is optimal, since the number of fish is only related to the number of times that John has been fishing in the lake, regardless of the total number of fishing trips. A total of fishing time can be fished for a time, each in the N lake select the most fish of a lake fishing.
A greedy algorithm was used to construct John's fishing plan.
Can think of John from a lake "instantaneous transfer" to there is also a lake, that is, at random moment can be from Lake 1 to the lake in the POS select one of the fish fishing.


Procedure Implementation code:

//from Lake 1  up to Lake pos , take time to Span class= "Hljs-keyword" >time (excluding distance) of the fishing plan void greedy (int  pos , int  time ) {if  (time  <= 0 ) Span class= "Hljs-keyword" >return ;  // time has run out int  i, J;  int  FISH[MAXN];  int  P[MAXN];   int  t = 0 ; for    (i = 0 ; i < pos ; ++i) fish[i] = F[i];   Memset (p, 0 , sizeof (p)); ...} 
//In time, choose the most fish in the lake fishing; If the fish are gone, put the time on the Lake 1. for(i =0; I < time; ++i) {intMax =0;//Fish in the most lakes, the number of fish    int ID= -1;//Number of the lake with the most fish    //Find the most fish in the lake. Number of fish and number of the lake     for(j =0; J < Pos; ++J)if(Fish[j] > Max) {max = fish[j];ID= J; }if(ID!= -1)//found, fishing handled{++p[ID]; fish[ID]-= d[ID];   T + = max; }//Not found (from Lake 1 to Lake Pos all finished), put time on Lake 1    Else++p[0]; }
//processing best practices   (T > Best) {best = t;  //Optimal value  memset   (Plan, 0 , sizeof  (Plan)); for   (i = 0 ; i < POS; ++i) //optimal solution  plan[i] = p[i]; }
输出钓鱼计划时。再把5乘回去。就变成实际的钓鱼时间(分钟):for (i=0; i<n-1; ++i)     printf("%d, "5);printf("%d\n", plan[n-15printf("Number of fish expected: %d\n", best);

Implementation code:

#include <iostream>#include <queue>using namespace STD;structData {intF,d,id;} a[ -],b;intn,t,tran[ -],x,ans,maxi,save[ -],tmp[ -],tt;priority_queue <data> Q;BOOL operator< (data A,data b) {if(A.F==B.F)returna.id>b.id;Else returnA.f<b.f;}intMain () { while(~scanf("%d", &n)) {if(n==0) Break;scanf("%d", &t); T *= A; for(intI=1; i<=n;i++)scanf("%d", &AMP;A[I].F); for(intI=1; i<=n;i++) {scanf("%d", &AMP;A[I].D);          A[i].id = i; } tran[1] =0; for(intI=2; i<=n;i++) {scanf("%d", &x); Tran[i] = tran[i-1] + x; } ans =-1;memset(Save,0,sizeof(save)); for(intI=1; i<=n;i++) {maxi =0;memset(TMP,0,sizeof(TMP)); tt = T-tran[i]; while(!q.empty ()) Q.pop (); for(intj=1; j<=i;j++) Q.push (A[j]); while(tt>0) {b = Q.top ();                    Q.pop ();                    tt--;                    Maxi + = B.F;                    tmp[b.id]++; B.F-= B.D;if(b.f<=0) B.f =0;              Q.push (b); }if(Maxi>ans) {ans = maxi; for(intj=1; j<=i;j++) Save[j] = Tmp[j]; }          } for(intI=1; i<n;i++)printf("%d,", save[i]*5);printf("%d\n", save[n]*5);printf("Number of fish expected:%d\n\n", ans); }return 0;}

Summary of greedy algorithm

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.