牛客网暑期ACM多校训练营(第二场)D-money (dp)

题目链接

题意

一共有n件商店,每个商店买卖东西的价格和不同,白兔想用差价挣钱,每次只能携带一种物品,问白兔最多赚多少的钱,和对应的交易次数

AC

两个变量分别记录当前买东西和买东西的剩余财富,财富越大可以使得买下一件物品的损失更低,卖下一件东西的收益更高。枚举n个物品,维护最大财富值。

#include 
#define N 100005
#define P pair
#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 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;
}

你可能感兴趣的:(多校,练习)