Codeforces374-div2D Maxim and Array

Problem - 721D - Codeforces

Codeforces. Programming competitions and contests, programming community

$i$番目の要素が$a_i$の数列が与えられる.$k$回, 要素に$+x$か$-x$することが出来る.$\prod a_i$を最小化する.マイナス要素が奇数個の時,要素の掛け算は符号がマイナスになるので,要素が$-$なら$-x$, 要素が$+$なら$+x$を小さい順にしていく.偶数個の時は,絶対値が最小の要素を異符号にして後は同じ.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <cstring>
#include <algorithm>
#include <queue>
#include <map>
#include <set>

#define REP(i,k,n) for(int i=k;i<n;i++)
#define rep(i,n) for(int i=0;i<n;i++)
#define each(it,v) for(__typeof((v).begin()) it=(v).begin();it!=(v).end();it++)
#define INF 1<<30
#define mp make_pair

using namespace std;
typedef long long ll;
typedef pair<ll, ll> P;

struct abs_sort {
  bool operator()(P a, P b) const {
      if(abs(a.first) != abs(b.first)) return abs(a.first) > abs(b.first);
      if(a.first != b.first) return a.first > b.first;
      return a.second > b.second;
  }
};


int main() {
  int n, k; ll x;

  cin >> n >> k >> x;

  ll vmin = INF, vcnt = 0;
  vector<ll> v(n);
  rep(i, n) {
      cin >> v[i];
      vmin = min(vmin, v[i]);

      if(v[i] < 0) vcnt++;
  }

  priority_queue<P, vector<P>, abs_sort> Q;
  rep(i, n) {
      Q.push(mp(v[i], i));
  }

  if(vcnt % 2 == 0) {
      P top = Q.top(); Q.pop();

      ll cnt = (abs(top.first) + 1) / x;
      if((abs(top.first) + 1) % x != 0) cnt++;

      if(cnt <= k) {
          k -= cnt;
      } else {
          cnt = k;
          k = 0;
      }

      if(top.first >= 0) {
          top.first -= cnt * x;
      } else {
          top.first += cnt * x;
      }

      Q.push(top);
  }

  rep(i, k) {
      P p = Q.top(); Q.pop();
      if(p.first >= 0) {
          Q.push(mp(p.first + x, p.second));
      } else {
          Q.push(mp(p.first - x, p.second));
      }
  }

  vector<P> ans;
  while(Q.size()) {
      P p = Q.top(); Q.pop();
      ans.push_back(mp(p.second, p.first));
  }

  sort(ans.begin(), ans.end());
  rep(i, n) {
      if(i) cout << " ";
      cout << ans[i].second;
  }
  cout << endl;
  
  return 0;
}
Oct 4th, 2016