BJFU ACM Online Judge 1549

Candy

时间限制(C/C++):1000MS/3000MS          运行内存限制:65536KByte
总提交:22            测试通过:12

描述

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个同学,每个同学有一个rating值。现在要给他们发糖果,规则:每个同学必须有一个,每个同学与他相邻的同学比较rating,rating高的一方得到更多的糖果。问最少需要多少糖果。


思路:假设初始每个人的糖果都为1,从前往后找如果他比他前一个人的rating大,那么更新这个人的糖果数。然后从后往前找如果前一个人比后一个人的rating高,更新此人糖果数。最后再从前往后找一下如果此人比前一人和后一人的rating都高 那么此人的糖果数为max(b[i-1],b[i+1])+1.求和即可。

#include
#include
#include
#include
#include
#define mv(a,b) memset(a,b,sizeof(a));
using namespace std;
typedef long long LL;
const int maxn=1000+10;
int a[maxn],b[maxn];
int main()
{
//	freopen("input.txt","r",stdin);
//	freopen("output.txt","w",stdout);
	int m;
	while(cin>>m)
	{
		mv(a,0);
		for(int i=1;i<=m;i++)
			cin>>a[i];
		for(int i=1;i<=m;i++)
			b[i]=1;
		a[0]=0;
		b[0]=0;
		for(int i=1;i<=m;i++)
		{
			if(a[i]>a[i-1])
				b[i]=b[i-1]+1;
		}
		for(int i=m;i>=1;i--)
		{
		    if(a[i]a[i-1]&&a[i]>a[i+1])
				b[i]=max(b[i-1],b[i+1])+1;
		}
		int ans=0;
		for(int i=1;i<=m;i++)
			ans+=b[i];
		cout<




你可能感兴趣的:(水题)