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:
- Each child must have at least one candy.
- Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?
初始化所有小孩糖数目为1,从前往后扫描,如果第i个小孩等级比第i-1个高,那么i的糖数目等于i-1的糖数目+1;
从后往前扫描,如果第i个的小孩的等级比i+1个小孩高,但是糖的数目却小或者相等,那么i的糖数目等于i+1的糖数目+1。
该算法时间复杂度为O(N)
#include<iostream>
#include<cstdio>
#include<vector>
using namespace std;
int candy(vector<int> &ratings)
{
vector<int> count(ratings.size(),1);
int i,len=count.size();
for(i=0;i<len;i++)
{
if(ratings[i+1]>ratings[i]&&count[i+1]<=count[i])
count[i+1]=count[i]+1;
}
for(i=len-1;i>=0;i--)
{
if(ratings[i-1]>ratings[i]&&count[i-1]<=count[i])
count[i-1]=count[i]+1;
}
int sum=0;
for(i=0;i<len;i++)
sum+=count[i];
return sum;
}
int main(int argc,char *argv[])
{
freopen("input.txt","r",stdin);
vector<int> v;
int num,tmp;
cin>>num;
while(num--)
{
cin>>tmp;
v.push_back(tmp);
}
cout<<candy(v)<<endl;
return 0;
}
这个题只要知道了模拟的方法,就比较简单了。