列表

详情


NC16632. money

描述

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

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

C++14(g++5.4) 解法, 执行用时: 361ms, 内存消耗: 4328K, 提交时间: 2018-07-23 08:54:53

#include<bits/stdc++.h>
#define ll long long 
#define M 100005
using namespace std;
ll a[M];
int t,n;
int main(){
	cin>>t;
	while(t--){
		cin>>n;
		ll A=0,B=0;
		for(int i=1;i<=n;i++)cin>>a[i];
		for(int i=1;i<=n-1;i++){
			A+=max((int)(a[i+1]-a[i]),0);
		}
		int cnt=1;
		for(int i=2;i<=n;i++){
			if(a[i]>a[i-1])cnt++;
			else if(a[i]<a[i-1]){
				if(cnt>=2)B+=2;
				cnt=1;
			}
		}
		if(cnt>=2)B+=2;
		cout<<A<<" "<<B<<endl;
	}
}

C++(g++ 7.5.0) 解法, 执行用时: 209ms, 内存消耗: 2364K, 提交时间: 2022-11-25 19:58:13

#include<iostream>
using namespace std;
int main()
{
	int q; cin >> q;
	while (q--)
	{
		int n; cin >> n;
		int*a = new int[n];
		for (int i = 0; i < n; i++) cin >> a[i];
		long long m = 0, s = 0, d = 0, w = 0;
		for (int i = 0; i < n - 1; i++)
		{
			if (a[i + 1] > a[i] && !d) w = a[i], d = 1, s++;
			if (d&&a[i + 1] < a[i]) m += a[i] - w, d = 0, s++;
		}
		if (d) m += a[n - 1] - w, s++;
		cout << m << ' ' << s << endl;
	}
}

C++11(clang++ 3.9) 解法, 执行用时: 324ms, 内存消耗: 2540K, 提交时间: 2018-07-21 14:30:05

#include<iostream>
using namespace std;
int main(){
	int q;
	cin>>q;
	while(q--){
		int n;cin>>n;
		int*a=new int[n];
		for(int i=0;i<n;i++) cin>>a[i];
		long long m=0,s=0,d=0,w=0;
		for(int i=0;i<n-1;i++){
			if(a[i+1]>a[i]&&!d) w=a[i],d=1,s++;
			if(d&&a[i+1]<a[i]) m+=a[i]-w,d=0,s++;
		}
		if(d) m+=a[n-1]-w,s++;
		cout<<m<<' '<<s<<endl;
	}
}

Python3(3.5.2) 解法, 执行用时: 435ms, 内存消耗: 24652K, 提交时间: 2020-04-25 18:10:38

T=int(input())
for _ in range(T):
    n=int(input())
    a=[int(e) for e in input().split()]+[-1]
    cur=a[0]
    ans1,ans2=0,0
    for i in range(0,len(a)):
        if a[i]<a[i-1] and i!=0:
            if a[i-1]>cur:
                ans1+=a[i-1]-cur
                ans2+=2
            cur=a[i]
    print(ans1,ans2)

上一题