码迷,mamicode.com
首页 > 其他好文 > 详细

candy

时间:2015-02-04 14:36:41      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:

There are N children standing in a line. Each child is assigned a rating value.

You are giving candies to these children subjected to the following requirements:

  • Each child must have at least one candy.
  • Children with a higher rating get more candies than their neighbors.

What is the minimum candies you must give?

解题思路:用了比较麻烦的方法,遍历两遍数组,第一遍对于确保右边比左边的人拿到的糖果符合条件;第二遍遍历来修正左边对于右边的情况;

#include<iostream>
#include<vector>
#include<numeric>
using namespace std;

int candy(vector<int> &ratings) {

	int ChildrenNum = ratings.size();
	vector<int>CandyVector(ChildrenNum, 1);
	for (int i = 0; i < ChildrenNum-1;++i){
		if (ratings[i] < ratings[i + 1])
			CandyVector[i + 1] = CandyVector[i] + 1;
	}
	for (int i = ChildrenNum-1; i >0; --i){
		if (ratings[i] < ratings[i - 1]&&CandyVector[i]>=CandyVector[i-1])
			CandyVector[i - 1] = CandyVector[i] + 1;
	}
	return accumulate(CandyVector.begin(), CandyVector.end(), 0);
}


candy

标签:

原文地址:http://blog.csdn.net/li_chihang/article/details/43485903

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!