Alice is a teacher of kindergarten. She wants to give some candies to the children in her class. All the children sit in a line and each of them has a rating score according to his or her usual performance. Alice wants to give at least 1 candy for each children. Because children are somehow jealousy. Alice must give her candies according to their ratings subjects to for any adjacent 2 children if one's rating is higher than the other he/she must get more candies than the other. Alice wants to save money so she wants to give as few as candies in total.
Input
The first line of the input is an integer N
, the number of children in Alice's class. Each of the followingN
lines contains an integer indicates the rating of each child.
Output
On the only line of the output print an integer describing the minimum number of candies Alice must give.
Sample Input
3
1
2
2
Sample Output
4
My Answer
(I am no sure if it is correct.)#include "stdafx.h" #include <iostream; using namespace std; class child { public: child() : m_candy(1) {} child(int rating) : m_rating(rating), m_candy(1) {} int Rating() { return m_rating; } void setRating(int rate) { m_rating = rate; } int Candy() { return m_candy; } void setCandy(int candies) { m_candy = candies; } private: int m_rating; int m_candy; }; void showCandies(int[], int); int _tmain(int argc, _TCHAR* argv[]) { const int count = 10; int childs_rating[] = {9,2,3,3,3,2,1,1,3,4}; showCandies(childs_rating, count); cin.get(); return 0; } void showCandies(int* rating, int count) { child* childs = new child[count]; for(int i=0;i<count;i++) { childs[i].setRating(rating[i]); } bool run = false; do { run = false; for(int i=0;i<count-1;i++) { if( childs[i].Rating() ; childs[i+1].Rating() && childs[i].Candy() <= childs[i+1].Candy()) { run = true; childs[i].setCandy(childs[i+1].Candy() + 1); } if( childs[i+1].Rating() ; childs[i].Rating() && childs[i+1].Candy() <= childs[i].Candy()) { run = true; childs[i+1].setCandy(childs[i].Candy() + 1); } } for(int i=0;i<count;i++) { cout << childs[i].Candy() << '\t'; } cout << endl; } while(run); delete[] childs; }
Reference:
http://stackoverflow.com/questions/11292913/candies-interviewstreet
沒有留言:
張貼留言