[PAT甲级]1172 Panda and PP Milk
以下所述均为个人理解,如有错误,还望指正
题目
PP milk (盆盆奶)is Pandas' favorite. They would line up to enjoy it as show in the picture. On the other hand, they could drink in peace only if they believe that the amount of PP milk is fairly distributed, that is, fatter panda can have more milk, and the ones with equal weight may have the same amount. Since they are lined up, each panda can only compare with its neighbor(s), and if it thinks this is unfair, the panda would fight with its neighbor.
Given that the minimum amount of milk a panda must drink is 200 ml. It is only when another bowl of milk is at least 100 ml more than its own that a panda can sense the difference.
Now given the weights of a line of pandas, your job is to help the breeder(饲养员)to decide the minimum total amount of milk that he/she must prepare, provided that the pandas are lined up in the given order.
Input Specification:
Each input file contains one test case. For each case, first a positive integer nnn (≤104\le 10^4≤104) is given as the number of pandas. Then in the next line, nnn positive integers are given as the weights (in kg) of the pandas, each no more than 200. the numbers are separated by spaces.
Output Specification:
For each test case, print in a line the minimum total amount of milk that the breeder must prepare, to make sure that all the pandas can drink in peace.
题解
想让熊猫左右不打架,就可以分别对其前缀和后缀进行求解,先正向遍历,使熊猫不与左边的熊猫打架,再反向遍历,使其不与右边的熊猫打架,最后结果再取正反向中较大的值相加即为结果。
#include <bits/stdc++.h>
using namespace std;
int weights[10010];
int milk1[10010];
int milk2[10010];
int main()
{
int N;
cin >> N;
for (int i = 0; i < N; i++)
{
cin >> weights[i];
}
int former, latter;
//先正序,保证其不与左边的熊猫打架
milk1[0]=200;
for (int i = 1; i < N ; i++)
{
former = i - 1;
if (weights[i] > weights[former])
{
milk1[i]=milk1[former] +100;
}
else if(weights[i]==weights[former])
{
milk1[i]=milk1[former];
}
else
{
milk1[i]=200;
}
}
//再逆序,保证其不与右边的熊猫打架
milk2[N-1]=200;
for (int i = N-2; i>=0; i--)
{
latter = i +1;
if (weights[i] >weights[latter]&&milk2[i]<milk2[latter])
{
milk2[i]=milk2[latter]+100;
}
else if(weights[i]==weights[latter])
{
milk2[i]=milk2[latter];
}
else
{
milk2[i]=200;
}
}
long int sum=0;
for(int i=0;i<N;i++)
{
sum+=max(milk1[i],milk2[i]);
}
cout<<sum;
}
AC结果: