[数据结构]K-Max Sum

C.K-Max Sum

Description

Here there is a very classical problem --- Max Sum!

Let's review the classsical problem:

Given a sequence a[1], a[2], a[3] ...... a[N], your job is to calculate the max sum of a sub-sequence and the sub-sequence's length must equals M.

But today, before you do the calculations, you are allowed to execute at most K consecutive operations. every operation, you can select an arbitrary number from the sequence and multiply it by 2. In addition, you must know that each number can only multiply once!

See example for more details!

Input

There are some test cases.

For each test case: There is a N, M (1 <= M <= N <= 100,000) - the number of elements in the sequence and the length of the chosen sub-sequence of the sequence!

Then N integers followed. (all the integers are between -10^9 and 10^9).The third line contains a single integer K (0 <= K <= N) the maximum allowed number of operations!

Output

Output the answer for the above problem.

Sample Input

3 3

1 2 3

2

5 3

1 -2 3 -4 5

2

Sample Output

11

12


本题没有过。超时。

使用multimap维护当前(i-m,i]区间的前k大。

#include <cstdio>
#include <map>
#include <functional>
using std::less;
using std::greater;
using std::multimap;
using std::make_pair;

const int maxn = 100010;

typedef multimap<int,int,greater<int> >::iterator iter;
iter it;
multimap<int,int,greater<int> > tree;

int sum[maxn];
int num[maxn];


int main()
{
//	freopen("a.in","r",stdin);

	int n,m;
	while (scanf("%d%d",&n,&m)==2)
	{
		tree.clear();
		for (int i=1;i<=n;i++)
		{
			scanf("%d",num+i);
			sum[i] = sum[i-1] + num[i];
		}

		int k;
		scanf("%d",&k);

		int ans = 0;
		for (int i=1;i<=n;i++)
		{
			int _ans = 0;
			if (i < m)
			{
				if (num[i]>0) tree.insert(make_pair(num[i],i));
			}
			else
			{
				if (num[i]>0) tree.insert(make_pair(num[i],i));

				while (!tree.empty() && i-tree.begin()->second > m)
				{
					tree.erase(tree.begin());
				}

				int c = 0;
				for (iter it=tree.begin();c<k && it!=tree.end();it++,c++)
				{
					_ans += it->first;
				}

				_ans += sum[i] - sum[i-m];
				//printf("Debug %d\n",_ans);
			}

			if (_ans > ans)
				ans = _ans;
		}

		printf("%d\n",ans);
	}

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值