There are NN children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
(1) Each child must have at least one candy.
(2) Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?
Input:
The input consists of multiple test cases.
The first line of each test case has a number NN, which indicates the number of students.
Then there are NN students rating values, 1 \leq N \leq 300, 1 \leq values \leq 100001≤N≤300,1≤values≤10000.
Output:
The minimum number of candies you must give.
输入:
5
1 2 3 4 5
5
1 3 5 3 6
输出:
15
9
题解
简单回溯,新建一个数组,将数组先从前往后扫描一遍,后一个数比前一个数大,就在前一个数基础上+1,然后再从后往前扫描一遍,同样后一个数比前一个数大,就在前一个数基础上+1,但是如果这个位置已经有数字了,就需要判断一次,将较大的数录入,最后将数组里的数字全部加起来输出就好。
代码
#include <iostream>
using namespace std;
int main()
{
int n;
int list[400] = {0};
int hasaki[400] = {0};
while(cin >> n)
{
for(int i = 0; i < n; i++)
{
cin >> list[i];
hasaki[i] = 1;
}
int count = 0;
for(int i = 1; i <= n; i++)
{
if(list[i] > list[i-1])
{
hasaki[i] = hasaki[i-1] + 1;
}
}
for(int i = n - 2; i >= 0; i--)
{
if(list[i] > list[i+1])
{
if(hasaki[i] < hasaki[i+1]+1)
hasaki[i] = hasaki[i+1] + 1;
}
}
for(int i = 0; i < n ;i++)
count += hasaki[i];
cout << count <<endl;
}
return 0;
}