题目:
Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i(1 ≤ i ≤ n) and replaces the i-th element of array ai either with ai + x or with ai - x. Please note that the operation may be applied more than once to the same position.
Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. ) can reach, if Maxim would apply no more than k operations to it. Please help him in that.
Input
The first line of the input contains three integers n, k and x (1 ≤ n, k ≤ 200 000, 1 ≤ x ≤ 109) — the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively.
The second line contains n integers a1, a2, ..., an ( ) — the elements of the array found by Maxim.
Output
Print n integers b1, b2, ..., bn in the only line — the array elements after applying no more than k operations to the array. In particular, should stay true for every 1 ≤ i ≤ n, but the product of all array elements should be minimum possible.
If there are multiple answers, print any of them.
Examples
input
5 3 1
5 4 3 5 2
output
5 4 3 5 -1
input
5 3 1
5 4 3 5 5
output
5 4 0 5 5
input
5 3 1
5 4 4 5 5
output
5 1 4 5 5
input
3 2 7
5 4 2
output
5 11 -5
题意:一段序列,每次可以将其中任意一个数增加或减少x,有k次操作,问k次操作后这个序列的最小乘积
题解:
贪心+优先队列:
先看一下序列中负数有多少个
①如果是奇数个,那么乘积就是负数,也就是接下来的操作肯定是让正的加大,负的减小。每次寻找一个绝对值最小的数操作就可以了。
②如果是偶数个,那么乘积就是正数,也是考虑绝对值,先操作绝对值最小的那个数,直到那个数字的符号发生变化就停止操作,接下来就是第①步。
因为绝对值最小的是拉低乘积大小的,所以需要修改绝对值最小值
注意当有偶数个负数并且绝对值最小为0时,我的0是只能减少的,因为只有减少才能让乘积变成负数!!!这里还WA了!!!
以后碰到题目要考虑选择最小,跟每次选择最小的区别,每次都选择最小那么每次新状态都要排序(用优先队列),以前经常忽略了这个问题,每次盯着那个最小值不停操作,实际上某些时候它早已不是最小值了。。。
代码:
#include<bits/stdc++.h>
#define LL long long
#define N 200005
using namespace std;
int t,n,tot=0;
LL a[N],k,ans[N];
struct ljh
{
LL x,y;
int id;
bool operator < (const ljh&a)const
{
return a.y<y;
}
}e[N];
bool cmp(ljh u,ljh v)
{
return u.y<v.y;
}
priority_queue<ljh>q;
int main()
{
cin>>n>>t>>k;
for(int i=1;i<=n;i++)
{
cin>>e[i].x;
e[i].y=abs(e[i].x);
e[i].id=i;
if(e[i].x<0)tot++;
}
if(tot%2==0)
{
sort(e+1,e+n+1,cmp);
if(e[1].x<0)//这个地方当e[1].x=0的时候不能进入,因为这个时候每次e[1].x是增加k的,他并没有改变所有数中小于0的数量
{
while(t&&e[1].x<=0)//等于0的时候继续增加,让它变成大于0,那样最后答案就是负数了
{
t--;
e[1].x+=k;
e[1].y=abs(e[1].x);
}
}
else//当e[1].x=0时,只能把他减少,不能增加,因为减少才能改变序列中负数的数量
{
while(t&&e[1].x>=0)//等于0时候继续减少,让答案变成负数
{
t--;
e[1].x-=k;
e[1].y=abs(e[1].x);
}
}
}
for(int i=1;i<=n;i++)q.push(e[i]);
while(t)
{
ljh now=q.top();
q.pop();
if(now.x>=0)now.x+=k;
else now.x-=k;
now.y=abs(now.x);
q.push(now);
t--;
}
while(!q.empty())
{
ans[q.top().id]=q.top().x;
q.pop();
}
for(int i=1;i<=n;i++)cout<<ans[i]<<" ";
return 0;
}