您的位置:首页 > 其它

Hackerrank :Candies

2015-12-10 20:31 288 查看


Candies

Problem Statement

Alice is a kindergarden teacher. She wants to give some candies to the children in her class. All the children sit in a line ( their positions are fixed), and each of them has a rating score according to his or her performance in the class. Alice wants to
give at least 1 candy to each child. If two children sit next to each other, then the one with the higher rating must get more candies. Alice wants to save money, so she needs to minimize the total number of candies given to the children.

Input Format

The first line of the input is an integer N, the number of children in Alice's class. Each of the following N lines contains an integer that indicates the rating of each child.

1 <= N <= 105

1 <= ratingi <=
105

Output Format

Output a single line containing the minimum number of candies Alice must buy.

Sample Input

[code]3  
1  
2  
2


Sample Output

[code]4


Explanation

Here 1, 2, 2 is the rating. Note that when two children have equal rating, they are allowed to have different number of candies. Hence optimal distribution will be 1, 2, 1.

题意:一堆小孩站成一排,每个小孩有一个分数,现在给各个小孩发糖果,每个小孩最少是一个糖果,如果这个小孩的分数比相邻小孩分数高,那么他得到的糖果也要比相邻小孩糖果多。问一共最少需要多少糖果。

从左到右扫一遍,从右到左扫一遍,求出每一个位置要求的最大值,相加得到结果。

代码:

#pragma warning(disable:4996)
#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <string>
#include <cstring>
#include <set>
#include <queue>
#include <stack>
#include <map>
using namespace std;
typedef long long ll;

#define INF 0x7fffffff
const int maxn = 100005;

int n, m;
int rating[maxn];
int dp1[maxn];
int dp2[maxn];

void input()
{
	int i;
	scanf("%d", &n);
	for (i = 1; i <= n; i++)
	{
		scanf("%d", &rating[i]);
		dp1[i] = 1;
		dp2[i] = 1;
	}
}

void solve()
{
	int i;
	for (i = 2; i <= n; i++)
	{
		if (rating[i] > rating[i - 1])
		{
			dp1[i] = dp1[i - 1] + 1;
		}
	}
	for (i = n-1; i >=1 ; i--)
	{
		if (rating[i] > rating[i + 1])
		{
			dp2[i] = dp2[i + 1] + 1;
		}
	}
	ll res = 0;
	for (i = 1; i <= n; i++)
	{
		res += max(dp1[i], dp2[i]);
	}
	cout << res;
}

int main()
{
	//freopen("i.txt","r",stdin);
	//freopen("o.txt","w",stdout);

	input();
	solve();

	//system("pause");
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: