计蒜网 Candy (模拟&技巧)

来源:互联网 发布:人工智能股票有哪些 编辑:程序博客网 时间:2024/06/13 05:51

Candy

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 100001N300,1values10000.

Output:

The minimum number of candies you must give.

样例1

输入:

51 2 3 4 55 1 3 5 3 6

输出:

159
//题意:输入n,接下来有n个数
表示n个人的身高,现在规定高的人得到的蜡烛数要比他旁边矮的人的蜡烛数多,问最少的蜡烛数是多少?
//思路:
可以从头开始判断,一直找连续的递减的序列,找到后就将这个递减序列赋值,表示他获得的蜡烛数,然后再继续向后找,直到找完为止。
最后累加求和即可。
赋值的时候有技巧,得注意,看代码
#include<stdio.h>#include<string.h>#include<algorithm>#include<iostream>using namespace std;int a[310];int dp[310];int main(){int n,i,j,k;while(scanf("%d",&n)!=EOF){memset(dp,0,sizeof(dp));dp[0]=1;int x,y;int sum=0;for(i=0;i<n;i++)scanf("%d",&a[i]);k=a[0];int cnt=1,m=0,s=0,e,kk;for(i=1;i<n;i++){if(k>=a[i]){cnt++;if(k==a[i])m++;}else{e=i;if(cnt==1)dp[i-1]=dp[i-2]+1;else{if(cnt-m<dp[s-1]+1)sum+=dp[s-1]+1-(cnt-m);dp[s]=cnt-m;kk=a[s];for(j=s+1;j<e;j++){if(a[j]==kk)dp[j]=dp[j-1];elsedp[j]=dp[j-1]-1;kk=a[j];}}s=e;cnt=1;m=0;}k=a[i];}if(cnt==1)dp[n-1]=dp[n-2]+1;else{if(cnt-m<dp[s-1]+1)sum+=dp[s-1]+1-(cnt-m);dp[s]=cnt-m;kk=a[s];for(j=s+1;j<n;j++){if(a[j]==kk)dp[j]=dp[j-1];elsedp[j]=dp[j-1]-1;kk=a[j];}}for(i=0;i<n;i++)sum+=dp[i];printf("%d\n",sum);}return 0;}

0 0