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

链接:https://www.nowcoder.com/acm/contest/140/D
来源:牛客网
 

题目描述

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.

输入描述:

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].

输出描述:

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

示例1

输入

1
5
9 10 7 6 8

输出

3 4

思路:

dp[i][0/1]表示已经访问完了i个商店,你手中是否有商品,此时的最大收益。

cou[i][0/1]表示当f[i][j]取最大值时最少的交易次数。  

(dp每次只要和前一个dp去比较就好了,我昨天比赛时每次从1开始遍历,结果就超时了。唉。今天改了一个符号就过了。)

代码:

#include<iostream>
#include<cstring>
#include<cmath>
#include<map>
#include<cstdio>
using namespace std;
const int mmax=100009;
int a[mmax];
long long int dp[mmax][2];
int cou[mmax][2];
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int n;
        scanf("%d",&n);
        memset(a,0,sizeof(a));
        for(int i=1;i<=n;i++)
        {
           scanf("%d",&a[i]);
        }
        memset(dp,0,sizeof(dp));
        memset(cou,0,sizeof(cou));
        long long int Max=0;
        dp[1][0]=0;
        dp[1][1]=-a[1];
        cou[1][0]=0;
        cou[1][1]=1;
        for(int i=2;i<=n;i++)
        {
            for(int j=i-1;j<i;j++)
            {

                dp[i][0]=max(dp[i][0],dp[j][0]);
                dp[i][0]=max(dp[i][0],dp[j][1]+a[i]);
                dp[i][1]=max(dp[i][0],dp[j][1]);
                dp[i][1]=max(dp[j][1],dp[i][0]-a[i]);
            }
            if(dp[i][0]==dp[i-1][1]+a[i])cou[i][0]=cou[i-1][1]+1;
            if(dp[i][1]==dp[i-1][0]-a[i])cou[i][1]=cou[i-1][0]+1;
            if(dp[i][0]==dp[i-1][0])cou[i][0]=cou[i-1][0];
            if(dp[i][1]==dp[i-1][1])cou[i][1]=cou[i-1][1];
            Max=max(dp[i][0],Max);
            Max=max(dp[i][1],Max);
        }printf("%lld ",Max);
        if(dp[n][0]>dp[n][1])printf("%d\n",cou[n][0]);
        else if(dp[n][0]<dp[n][1])printf("%d\n",cou[n][1]);
        else printf("%d\n",min(cou[n][0],cou[n][1]));

    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/zero_979/article/details/81152049