山东省第八届ACM大学生程序设计竞赛 --- company (贪心+前缀和)

Problem Description

There are n kinds of goods in the company, with each of them has a inventory of and direct unit benefit . Now you find due to price changes, for any goods sold on day i, if its direct benefit is val, the total benefit would be i⋅val.
Beginning from the first day, you can and must sell only one good per day until you can’t or don’t want to do so. If you are allowed to leave some goods unsold, what’s the max total benefit you can get in the end?

Input

The first line contains an integers n(1≤n≤1000).
The second line contains n integers val1,val2,..,valn(−100≤.≤100).
The third line contains n integers cnt1,cnt2,..,cntn(1≤≤100).

Output

Output an integer in a single line, indicating the max total benefit.

Sample Input

4
-1 -100 5 6
1 1 1 2

Sample Output

51

Hint

sell goods whose price with order as -1, 5, 6, 6, the total benefit would be -1*1 + 5*2 + 6*3 + 6*4 = 51.

题意: 给你n种物品,它们的价值是val,数量是cnt,如果第m天你卖掉一件商品i,那么你的收入是m*val[i],要求,从第一天开始到你想停止的一天,使得你的收入最大。

思路: 将每个价值保存到数组(数量拆开),然后从小到大排序,按照该序列计算暂时的价值ans , 然后从左到右遍历,如果不需要这个价值就去除,然后更新ans;
更新ans = ans - s[i] - (sum[cnt-1]-sum[i]) sum是前缀和
这里写图片描述

AC代码:

#include<bits/stdc++.h>
using namespace std;
struct node
{
    int c;
    int v;
};
node p[1005];
const int maxn = 1e5+5;
int s[maxn];
typedef long long LL;
LL sum[maxn];
LL ans = 0;
int main()
{
    #ifdef LOCAL
    freopen("in.txt","r",stdin);
    #endif // LOCAL
    ios_base::sync_with_stdio(false);
    cin.tie(NULL),cout.tie(NULL);
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
        cin>>p[i].v;
    for(int i=0;i<n;i++)
        cin>>p[i].c;
    int cnt = 0;
    for(int i=0;i<n;i++)
    {
        for(int j=1;j<=p[i].c;j++)
            s[cnt++] = p[i].v;
    }
    sort(s,s+cnt);
    sum[0] = s[0];
    ans = sum[0];
    for(int i=1;i<cnt;i++)
    {
        sum[i] = sum[i-1]+s[i];
        ans += (i+1)*s[i];
    }
    for(int i = 0;i<cnt;i++)
    {
        LL res = ans-s[i]-(sum[cnt-1] - sum[i]);
        if(res>ans)
            ans = res;
        else
            break;
    }
    cout<<ans<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_37624640/article/details/80033270