Hackerrank :Candies
2015-12-10 20:31
288 查看
Candies
Problem StatementAlice 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; }
相关文章推荐
- Cordova 用iOS做webApp壳
- 20151210 Jquery 学习笔记 AJAX 进阶
- 蓝桥杯 基础练习 杨辉三角形
- git提交步骤
- PAT乙级——1005 德才论 (C/C++)
- CCF真题之网络延时
- FlashFXP 4.3.1 注册码
- 暂保存
- 如何手工执行segment advisor(10g/11g)
- centos/win7上安装我的世界服务器、客户端
- php通过thrift 0.9.0操作HBase
- 。Java中的一些小细节
- 20151210--MVC
- Codeforces 605A
- DOTween -Init
- PAT乙级——1004 福尔摩斯的约会 (C/C++)
- 子父类中的构造函数
- String.format()【演示具体的例子来说明】
- 过河(bfs)
- 使用sqlplus连接提示:ORA-28002: the password will expire within 7 days