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;
}