欢乐暑假线上编程比赛第四题:分配糖果
题目详情:
有n个小朋友站成一排(编号从0到n-1),每个小朋友有一个rating值,存放在ratings数组中。老师需要给他们分配糖果,每个小朋友至少需要一颗糖果,对于任意相邻的两个小朋友i和i+1,rating值大的必须比rating值小的分配的糖果多(rating相同的没必要分配一样多的糖果)。
请计算最少需要多少颗糖果,才能完成上述分配。
输入格式:
多组数据,每组数据第一行是一个正整数n。
接下来n行,每行有1个正整数,表示每个小朋友的rating值。所有整数都不超过100000。
输出格式:
每组数据一行,包括一个正整数,表示做少需要的糖果数。
答题说明:
输入样例
3
1
2
2
输出样例:
4
我的程序如下:
#include "stdio.h"
#define N 100000
long fun(long *,long,long);
main()
{
long a[N],i,j,n,m,count,temp;
int flag;
count = 0;
flag = 0;
while(scanf("%ld",&n) != EOF)
{ //input people num
count = 0;
for(i=0;i<n;i++) //input everyone's rating
{
scanf("%ld",&a[i]);
}
temp = fun(a,0,n);
m = temp;
count += temp; //the code above be used to count the num of first people
for(i = 1;i < n-1;i++)
{
if(a[i] > a[i-1])
{
temp = fun(a,i,n);
if(m < temp)
m = temp;
else
m++;
}
else
{
temp = fun(a,i,n);
m = temp;
}
count += m;
}
if(a[i] > a[i-1])
{
m++;
count += m;
}
else
{
count++;
} //count the num of last people
printf("%d\n",count);
}
}
long fun(long *a,long xi,long xn)
{
long i;
long m;
m = 1;
for(i = xi;i < xn -1;i++)
{
if(a[i] > a[i+1])
{
m ++;
continue;
}
else
break;
}
return m;
}
仅供参考学习,不保证完全正确