计蒜网 Candy (模拟&技巧)

85 篇文章 0 订阅
34 篇文章 0 订阅

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

输入:

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

输出:

15
9
//题意:输入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];
						else
							dp[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];
				else
					dp[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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值