JZOJ 5274. 数组

来源:互联网 发布:matlab 无约束最优化 编辑:程序博客网 时间:2024/06/09 15:16

Description

Description

Input

Input

Output

Output

Sample Input

输入样例1:

3 2 7
5 4 2

输入样例2:

5 3 1
5 4 3 5 5

Sample Output

输出样例1:

999999732

输出样例2:

0

Data Constraint

Data Constraint

Solution

  • 显然,乘积最好是负数,这样会更优,那么用一个布尔型变量 Pd 表示当前的负数数量的奇偶性。

  • 因为加减操作的对象的值的绝对值一定是当前最小的,这样才会显得更优(贪心)。

  • 于是我们维护一个堆,取出其绝对值最小的那个,再对 Pd 分类讨论:

    1. 若负数数量为奇数,说明乘积为负数;

    2. 若负数数量为偶数,说明乘积为正数;

  • 再根据当前值的正负性来判断加减,之后压回堆中即可,时间复杂度 O(K log N)

Code

#include<cstdio>#include<cmath>#include<queue>using namespace std;typedef long long LL;const int N=2e5+1,mo=1e9+7;int n,k,x;int a[N];bool pd;struct data{    int id;    data(int x){id=x;}    friend bool operator <(data x,data y)    {        return abs(a[x.id])>abs(a[y.id]);    }};priority_queue<data>q;inline int read(){    int X=0,w=1; char ch=0;    while(ch<'0' || ch>'9') {if(ch=='-') w=-1;ch=getchar();}    while(ch>='0' && ch<='9') X=(X<<3)+(X<<1)+ch-'0',ch=getchar();    return X*w;}int main(){    n=read(),k=read(),x=read();    for(int i=1;i<=n;i++)    {        a[i]=read();        if(a[i]<0) pd=!pd;        q.push(data(i));    }    while(k--)    {        int t=q.top().id;        q.pop();        if(a[t]<0)        {            if(pd) a[t]-=x; else a[t]+=x;            if(a[t]>=0) pd=!pd;        }else        {            if(pd) a[t]+=x; else a[t]-=x;            if(a[t]<0) pd=!pd;        }        q.push(t);    }    LL ans=1;    for(int i=1;i<=n;i++) ans=ans*a[i]%mo;    printf("%lld",(ans+mo)%mo);    return 0;}