牛客网暑期ACM多校训练营(第二场)-D-money(贪心,物品买卖)

题目链接: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

题目大意:T组测试样例,对于每组样例,一个n代表n个数,然后是n个数,表示第i天的商品的价值;只能往前走不能后退,问走完一遍的能够获得的最大收益,同时的最少交易次数;

注意,这里的物品只能拿一个(想要那新的必须放弃(卖掉)手中的)

物品买卖的题,贪心似乎很好写;

ac:

#include<stdio.h>
#include<string.h> 
#include<math.h> 
   
#include<map>  
//#include<set>
#include<deque> 
#include<queue> 
#include<stack> 
#include<bitset>
#include<string> 
#include<fstream>
#include<iostream> 
#include<algorithm> 
using namespace std; 
 
#define ll long long 
#define INF 0x3f3f3f3f 
//#define mod 1e9+7
//#define max(a,b) (a)>(b)?(a):(b)
//#define min(a,b) (a)<(b)?(a):(b)
#define clean(a,b) memset(a,b,sizeof(a))// 水印
//std::ios::sync_with_stdio(false);
 
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        int n;
        scanf("%d",&n);
        ll cnt=0,ans=0,have;
        bool f=0;
        for(int i=1;i<=n;++i)
        {
            ll x;
            scanf("%lld",&x);
            if(i==1)
                have=x;
            if(have<x)//有收益
            {
                ans=ans+x-have;//收益
                if(f==0)//如果手中没东西
                    cnt++;//使用have的交换
                have=x;//换成x
                f=1;//手中有东西了
            }
            else if(have>x)//如果没有收益(现在这个比手中的这个还要小)
            {
                f=0;
                have=x;//原来的那个都不用拿,选择那这个
            }
            //cout<<ans<<" "<<cnt<<endl;
        }
        printf("%lld %lld\n",ans,cnt*2);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40482358/article/details/82186787