Candy

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?

Input:

The input consists of multiple test cases.

The first line of each test case has a number NNN, which indicates the number of students.

Then there are NNN students rating values, 1≤N≤300,1≤values≤100001 \leq N \leq 300, 1 \leq values \leq 100001N300,1values10000.

Output:

The minimum number of candies you must give.

样例1

输入:

5
1 2 3 4 5
5 
1 3 5 3 6

输出:

15
9
 
 
 
 
#include<stdio.h>
int a[1000],b[1000];
int Max(int a,int b)
{
    return a>b?a:b;
}
int main()
{
    int n,i,p,r,j,f;
    while(scanf("%d",&n)!=-1)
    {
        for(i=0; i<n; i++)
        {
            scanf("%d",&a[i]);
        }
        b[0]=1;
        for(i=1; i<n; )
        {
            if(a[i]>a[i-1])
            {
                b[i]=b[i-1]+1;
                i++;
            }
            if(a[i]==a[i-1])
            {
                b[i]=b[i-1];
                i++;
            }
            if(a[i]<a[i-1])//先找到后面的数小于它前面的数的位置,记住下标
            {
                int p,val;
                p=i-1,val=b[p];
                int qq=1;
                while(a[i]<=a[i-1]&&i<n) i++;//找到后面的数大于它前面的数的位置,记住下标
                b[i-1]=qq;
              //  printf("%d %d\n",i-2,p);
                for(j=i-2;j>=p;j--)//给p和i-2之间倒着赋值
                {
                    if(a[j]==a[j-1]) b[j]=qq;
                    else b[j]=++qq;
                }
                b[p]=Max(b[p],val);比较倒着赋值之后的b[p]和同一个位置的val大小,并把b[p]为最大的那一个
            }
        }
        int h=0;
        for(i=0; i<n; i++)
        {
            h+=b[i];//加和
        }
        printf("%d\n",h);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值