Greedy algorithm of the cent candy

Source: Internet
Author: User
A few days ago a classmate recommended to me an algorithm problem, think for a while thought there, and then one night to the code out, and then did not think of is: "One into this topic deep like the sea, from this hair is passers-by."

——————————————————————— # # title # #

The meaning of the topic is as follows: Now you have a group of children in your family, stand in a row, you have to give them candy. Requirements are: The adjacent two people, the age of the large number of candies to be divided more, (if the adjacent two persons of the same age, the number of sweets in the two sizes are not required). Your goal is to meet these kids ' requirements with the least amount of sweets.
The topic understanding is quite simple, the interested schoolmate may think first. This is the time to test your IQ.
Next, I will give my own answer. For reference only.
I just saw a little "greedy algorithm" some time ago. After seeing the topic, it is natural to design the "greedy" aspect. (greedy algorithm is simply to solve a large problem of the optimal solution, each small step takes the current optimal strategy, finally get the overall optimal solution, still do not know their own Baidu bar) and then design the algorithm is: from the first person, give him a candy, let go back, if the latter a person than before a person of age, Then his candy was added one on the basis of the previous man, if the latter person is younger than the previous one, then his candy on the basis of the previous one minus one, if the reduction to zero, we will find the first person candy has been reduced, from his beginning, and then each add a candy.
For example, the age of this group of children is as follows: 3,5,10,9,4,3. Then this algorithm is the implementation of the process is the first person 1, the second person 2, the third person 3. The four individuals 2, the fifth person 1, at this time found that the sixth person has only 0, let just start from the third person, each add a candy. The last one can be divided into one. It was a pleasure to finish the task, and it took a little time to knock the code out. So happy.
Results a test, many results are not the optimal solution. Scared I can only reconsider the algorithm. After damaging some brain cells, it was found that the operation "minus one" would be a bug. For example, the above example removes the two people behind, that is, 3,5,10,9. According to the original algorithm is: 1,2,3,2. But you will find that the least distribution is actually: 1,2,3,1. This is just a simple example, and there are many more complex situations. So I decided to adjust the strategy: every time when the latter one is younger than the previous one, I give him a candy. When you meet someone without candy, the treatment is still the same.
After the code was changed, it was a lot, and then I found I hadn't considered the same situation. (the original question did not say equal how to do, the brain made up a bit) each encounter equal circumstances, just give him one. Other approaches remain unchanged.
Well, the design of the algorithm finally came to an end. But the next egg pain is the code. May be a long time no, even with this algorithm and then made up or wrong. It is not easy to realize it. such as how to record from who started down, and ... And so on details. Then start debugging, various changes, here omitted 1000 words ... Next, the code is attached:

int Candy (int* ratings, int ratingssize) {int min = 0;
    int number = 1;
    int current;
    int i;
    int count=0;
    int A;
        for (a = 0; a < ratingsSize-1; a++) {if (ratings[a]==ratings[a+1)} {break;
        else if (Ratings[a] > ratings[a + 1]) count++;
    else break;
    min = count+1;
            for (i = 1; i < ratingssize i++) {if (ratings[i]>ratings[i-1)) {number++;
        min = min + number;
            else if (ratings[i] = = Ratings[i-1]) {number = 1;
        min = min + number;
            else {count = 0; for (current = I, current < ratingssize current++) {if (ratings[current) < Ratings[cur
                    Rent-1]) {count++;
                min = min + count;
          } else      {break;
            } if (count>=number&&i!=1) {min=min+count-number+1;
            Number = 1;
        i = current-1;
    } return min; }
A few mistakes have been made, and after submission, a. Really Hard-won happiness, O (* ̄▽ ̄*) O.
Explain the code: the first for loop is to handle situations where the previous person's age is equal. Give each of them a straight one. (In fact, the cycle has not been changed, the time complexity of the two are similar). Number is to record the current amount of this person's candy, encountered after a person of age and equal to the current person, it is better to deal with. If the latter person is younger than the previous one, it will always find two people who are starting to rise in age. Count the number of sweets needed for this age-decreasing person. Although this program has a double loop, the actual time complexity is still O (n). Overall, this problem does not look very difficult, but to think of the various conditions of the algorithm is still a certain degree of difficulty, may miss some of the situation. This is the rigor of the algorithm. Suddenly remember to write an algorithm with a big guy, is an array of only one number appeared once, the other number has appeared three times, the number that appears once to find out. Results The algorithm logic misses some cases. In the exchange of time also affirmed that my algorithm is no problem, very simple explanation. The result is very awkward, serious one want to find out the situation, in fact, the algorithm is wrong. It's a slap in the face. The  
 algorithm is very challenging thinking things, can independently think of some algorithm problem is very fulfilling, especially found a better solution. Second, the design process, the logical relationship should be clear, otherwise it is easy to make mistakes or omissions. For example, I am not sure whether the above algorithm is consistent with all the circumstances, after all, the platform has only 29 test cases.

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.