CodeForces-721D-Maxim and Array(优先队列,贪心,分类讨论)

链接:

https://vjudge.net/problem/CodeForces-721D

题意:

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.

思路:

贪心对每一个绝对值最小的值处理,小于0就减,大于等于0就加.等于0注意要当大于0考虑.

代码:

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;

const int MAXN = 2e5+10;

struct Node
{
    int pos;
    LL val;
    bool operator < (const Node& that) const
    {
        return abs(this->val) > abs(that.val);
    }
}node[MAXN];
int n;
LL k, x;

void Solve()
{
    priority_queue<Node> que;
    for (int i = 1;i <= n;i++)
        que.push(node[i]);
    while (k)
    {
        Node now = que.top();
        que.pop();
        if (now.val >= 0)
            now.val += x;
        else
            now.val -= x;
        que.push(now);
        k--;
    }
    while (!que.empty())
    {
        node[que.top().pos] = que.top();
        que.pop();
    }
    for (int i = 1;i <= n;i++)
        printf("%lld ", node[i].val);
    printf("
");
}

int main()
{
    scanf("%d %d %lld", &n, &k, &x);
    int cnt = 0;
    for (int i = 1;i <= n;i++)
    {
        scanf("%lld", &node[i].val);
        node[i].pos = i;
        if (node[i].val < 0)
            cnt++;
    }
    if (cnt == 0)
    {
        int mpos = 1;
        for (int i = 1;i <= n;i++)
        {
            if (node[i].val < node[mpos].val)
                mpos = i;
        }
        LL ti = (node[mpos].val+1LL+x-1)/x;
        if (ti > k)
            node[mpos].val -= k*x;
        else
            node[mpos].val -= ti*x;
        k -= min(ti, k);
    }
    else if (cnt > 0 && cnt%2 == 0)
    {
        int mpos = 1;
        for (int i = 1;i <= n;i++)
        {
            if (abs(node[i].val) < abs(node[mpos].val))
                mpos = i;
        }
        if (node[mpos].val >= 0)
        {
            LL ti = (node[mpos].val+1LL+x-1)/x;
            if (ti > k)
                node[mpos].val -= k*x;
            else
                node[mpos].val -= ti*x;
            k -= min(ti, k);
        }
        else
        {
            LL ti = (abs(node[mpos].val)+1LL+x-1)/x;
            if (ti > k)
                node[mpos].val += k*x;
            else
                node[mpos].val += ti*x;
            k -= min(ti, k);
        }
    }
    Solve();

    return 0;
}
原文地址:https://www.cnblogs.com/YDDDD/p/11386423.html