【USACO2021 Air Cownditioning】题解
题目
Farmer John's cows N
are very particular about the room temperature in their barn. Some cows like the temperature to be on the cooler side, while others prefer more warmth.
Farmer John's barn contains a sequence of N
stalls, numbered 1…N, each containing a single cow. The i-th cow prefers the temperature of her stall to be pi, and right now the temperature in her stall is ti. In order to make sure every cow is comfortable, Farmer John installs a new air conditioning system that is controlled in a somewhat interesting way. He can send commands to the system telling it to either raise or lower the temperature in a consecutive series of stalls by 1 unit --- for example "raise the temperature in stalls 5…8
by 1 unit". The series of stalls could be as short as just a single stall.
Please help Farmer John determine the minimum number of commands he needs to send his new air conditioning system so that every cow's stall is at the ideal temperature for its resident cow.
Farmer John 的 N 头奶牛对他们牛棚的室温非常挑剔。有些奶牛喜欢温度低一些,而有些奶牛则喜欢温度高一些。
Farmer John 的牛棚包含一排 N
个牛栏,编号为 1…N,每个牛栏里有一头牛。 第 i 头奶牛希望她的牛栏中的温度是 pi,而现在她的牛栏中的温度是 ti。为了确保每头奶牛都感到舒适,Farmer John 安装了一个新的空调系统。该系统进行控制的方式非常有趣,他可以向系统发送命令,告诉它将一组连续的牛栏内的温度升高或降低 1 个单位——例如「将牛栏 5…8
的温度升高 1 个单位」。一组连续的牛栏最短可以仅包含一个牛栏。
请帮助 Farmer John 求出他需要向新的空调系统发送的命令的最小数量,使得每头奶牛的牛栏都处于其中的奶牛的理想温度。
思路
我们对于需要加的和需要减的分段考虑。
假设有一段是全部要加的。
我们只需要看一下每一个要比前一个多加多少,因为前一个能加的这个也能加,只需要考虑这一个不能加的即可。
要减的同理。
总结
对于此类题目,我们可以大胆猜测可以分情况讨论。同时在考虑变多少的时候,我们可以尝试和相邻的进行比较,看看新加的贡献。
Code
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define N 1000010
int n, m, i, j, k, ans;
int x[N], a[N], y[N];
signed main()
{
scanf("%lld", &n);
for(i=1; i<=n; ++i) scanf("%lld", &x[i]);
for(i=1; i<=n; ++i) scanf("%lld", &y[i]);
for(i=1; i<=n; ++i) a[i]=max((long long)0, x[i]-y[i]);
for(i=1, k=0; i<=n; ++i)
ans+=max((long long)0, a[i]-k), k=a[i];
for(i=1; i<=n; ++i) a[i]=max((long long)0, y[i]-x[i]);
for(i=1, k=0; i<=n; ++i)
ans+=max((long long)0, a[i]-k), k=a[i];
printf("%lld", ans);
return 0;
}
本文来自博客园,作者:zhangtingxi,转载请注明原文链接:https://www.cnblogs.com/zhangtingxi/p/15716347.html