标签:
描述
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:
(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?
输入
The input consists of multiple test cases.
The first line of each test case has a number N, which indicates the number of students.
Then there are N students rating values, 1 <= N <= 300, 1 <= values <= 10000.
输出
The minimum number of candies you must give.
样例输入
5
1 2 3 4 5
5
1 3 5 3 6
样例输出
15
9
题目来源
BJFUACM
题目大意:给你n个数字的序列,表示n个人的val值。现在给n个人发糖,每人至少发一个,如果某个人的val比旁边的人大,那么那个人必须获得更多的糖果。问你满足条件的情况下,最少要发出多少糖果。 如果某个人val比旁边的两个人都大,那么他应该获得比两旁所得糖果最大值还要多。
解题思路:要保证某人比两边的最大糖果数大。那么我们从左边扫一遍递增,从右边扫一遍递增。那么该位置所得糖果数,应该是两次当中的最大值。
#include<stdio.h> #include<algorithm> #include<string.h> #include<math.h> #include<string> #include<iostream> #include<queue> #include<vector> #include<set> using namespace std; typedef long long LL; #define mid (L+R)/2 #define lson rt*2,L,mid #define rson rt*2+1,mid+1,R const int INF = 0x3f3f3f3f; const int maxn = 1e3 + 300; int a[maxn],dp1[maxn],dp2[maxn]; int main(){ int n; while(scanf("%d",&n)!=EOF){ for(int i = 1; i <= n; i++){ scanf("%d",&a[i]); } memset(dp1,0,sizeof(dp1)); memset(dp2,0,sizeof(dp2)); for(int i = 1; i <= n; i++){ if(a[i] > a[i-1]){ dp1[i] = dp1[i-1]+1; }else{ dp1[i] = 1; } } for(int i = n; i >= 1; i--){ if(a[i] > a[i+1]){ dp2[i] = dp2[i+1] + 1; }else{ dp2[i] = 1; } } int sum = 0; for(int i = 1; i <= n; i++){ sum += max(dp1[i],dp2[i]); } printf("%d\n",sum); } return 0; }
标签:
原文地址:http://www.cnblogs.com/chengsheng/p/5436002.html