您的位置:首页 > 编程语言 > Go语言

How to solve the Candy problem?

2015-01-09 15:34 513 查看
The problem is:

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.

We can use the piece of code to solve the problem:

namespace
{
template <typename I>
size_t candy(I begin, I end)
{
int ret = 0;
int assignment = 1;
while ( begin < end ) {
I i = begin;
int sum = 0;

// what is the loop invariant?
size_t n = std::distance(begin, end);
if (n > 1) {
if (*i < *(i + 1)) {
while ((i + 1) < end && *i < *(i + 1)) {
sum += assignment;
++assignment;
++i;
}
}
else if (*i > *(i + 1)) {
I j = i;
while ((i + 1) < end && *i > *(i + 1)) {
sum += assignment;
--assignment;
++i;
}
if (assignment > 1) {
int v = assignment - 1;
v *= (static_cast<int>(i - j) - 1);
sum -= v;
}
else if (assignment < 1) {
int v = 1 - assignment;
v *= static_cast<int>(i - j);
sum += v;
}
assignment = 1;
}
else {
while ((i + 1) < end && *i == *(i + 1)) {
sum += assignment;
assignment = 1;
++i;
}
}
}
else {
sum += assignment;
++i;
}
ret  += sum;
begin = i;
}
return static_cast<size_t>(ret);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Algorithm
相关文章推荐