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

  • 2018-07-21
  • 17
  • 0

题目:

White Cloud has built n stores numbered from 1 to n.
White Rabbit wants to visit these stores in the order from 1 to n.
The store numbered i has a price a[i] representing that White Rabbit can spend a[i] dollars to buy a product or sell a product to get a[i] dollars when it is in the i-th store.
The product is too heavy so that White Rabbit can only take one product at the same time.
White Rabbit wants to know the maximum profit after visiting all stores.
Also, White Rabbit wants to know the minimum number of transactions while geting the maximum profit.
Notice that White Rabbit has infinite money initially.

Input:

The first line contains an integer T(0<T<=5), denoting the number of test cases.
In each test case, there is one integer n(0<n<=100000) in the first line,denoting the number of stores.
For the next line, There are n integers in range [0,2147483648), denoting a[1..n].

Output:

For each test case, print a single line containing 2 integers, denoting the maximum profit and the minimum number of transactions.

Sample Input:

1
5
9 10 7 6 8

Sample Output:

3 4

题目链接

White Rabbit从编号1 \rightarrow n遍历商店,每个商店都有一个价格a[i],White Rabbit抵达一个商店时可以选择以价格a[i]买商店里的商品或者以价格a[i]卖掉手中的物品,求White Rabbit遍历完商店之后的最大利润和买卖操作次数。

开一个dp数组dp[maxn][4]dp[i][0]代表在第i个商店以价格a[i]买入商品后的最大利润,dp[i][1]代表在第i个商店以价格a[i]卖出手中物品后的最大利润,dp[i][2]在第i个商店以价格a[i]买入商品后的买卖操作次数,dp[i][3]代表在第i个商店以价格a[i]卖出手中物品后的买卖操作次数。在遍历更新当前dp[i][x]dp[i][0]就等于j \in [1,i-1]dp[j][1]的最大值减a[i]dp[i][1]等于j \in [1,i-1]dp[j][0]的最大值加a[i],实时用变量维护更新两个最大值及其索引位置和dp[i][2]dp[i][3]

在题目所给样例中流程为:

i i个商店的价格a[i] 以价格a[i]卖出手中物品后的最大利润 以价格a[i]买入商品后的最大利润 j \in [1,i-1]dp[j][1]的最大值 j \in [1,i-1]dp[j][0]的最大值
1 9 -9 0 -9 0
2 10 -10 1 -9 1
3 7 -6 -2 -6 1
4 6 -5 0 -5 1
5 8 -7 3 -5 3

最后j \in [1,i-1]dp[j][0]的最大值即为最大利润,其索引位置的dp[index][3]即为买卖操作次数。

AC代码:

评论

还没有任何评论,你来说两句吧