牛客網暑期ACM多校訓練營(第二場)D-money (dp)
阿新 • • 發佈:2019-02-03
題意
一共有n件商店,每個商店買賣東西的價格和不同,白兔想用差價掙錢,每次只能攜帶一種物品,問白兔最多賺多少的錢,和對應的交易次數
AC
兩個變數分別記錄當前買東西和買東西的剩餘財富,財富越大可以使得買下一件物品的損失更低,賣下一件東西的收益更高。列舉n個物品,維護最大財富值。
#include <bits/stdc++.h>
#define N 100005
#define P pair<int,int>
#define mk(a, b) make_pair(a, b)
#define mem(a, b) memset(a, b, sizeof(a))
#define pb(a) push_back(a)
#define lowbit(a) a&(-a)
#define ll long long
using namespace std;
int inf = 0x3f3f3f3f;
int mod = 1e9 + 7;
int main(){
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
#endif
int t;
scanf("%d", &t);
while (t--) {
int n;
scanf("%d" , &n);
vector<ll> a(n + 1);
for (int i = 1; i <= n; ++i) {
scanf("%lld", &a[i]);
}
// mon_sell 記錄如果賣這件物品的最大錢數
// mon_buy 記錄如果買這件物品的最大錢數
ll mon_sell = 0, mon_buy = -a[1];
// time_buy 買這件物品交換的次數
// time_sell 賣這件物品交換的次數
ll time_sell = 0, time_buy = 1;
// 列舉每個物品
for (int i = 2; i <= n; ++i) {
ll selled = mon_buy + a[i];
ll buyed = mon_sell - a[i];
// 更新
if (selled > mon_sell) {
mon_sell = selled;
time_sell = time_buy + 1;
}else if(selled == mon_sell) {
time_sell = min(time_sell, time_buy + 1);
}
// 更新
if (buyed > mon_buy) {
mon_buy = buyed;
time_buy = time_sell + 1;
}else if(buyed == mon_buy) {
time_buy = min(time_buy, time_sell + 1);
}
}
printf("%lld %lld\n", mon_sell, time_sell);
}
return 0;
}