題目
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;
}