Codeforces Round #673 (Div. 2) D. Make Them Equal(数论/构造)

题目链接:https://codeforces.com/contest/1417/problem/D

题意

给出一个大小为 $n$ 的正整数数组 $a$ ,每次操作如下:

  • 选择 $i,j$ 和 $x$,$(1 \le i, j \le n,\ 0 \le x \le 10^9)$
  • 令 $a_i - x \cdot i,\ a_j + x \cdot i$

要求过程中不能有负数产生,问能否在 $3n$ 次操作内使数组中的每个元素相等,如果可以给出操作次数和过程。

题解

把每个 $a_i$ 变为 $i$ 的倍数后全部加给 $a_1$ ,最后从 $a_1$ 处均分即可。

证明

因为 $a_i \ge 1$,所以前 $i-1$ 个数一定可以补余使得第 $i$ 个数为 $i$ 的倍数。

代码

#include <bits/stdc++.h>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int t;
    cin >> t;
    while (t--) {
        int n;
        cin >> n;
        vector<int> a(n + 1);
        int sum = 0;
        for (int i = 1; i <= n; i++) {
            cin >> a[i];
            sum += a[i];
        }
        if (sum % n != 0) {
            cout << -1 << "\n";
            continue;
        }
        cout << 3 * (n - 1) << "\n";
        for (int i = 2; i <= n; i++) {
            cout << 1 << ' ' << i << ' ' << (i - (a[i] % i)) % i << "\n";
            cout << i << ' ' << 1 << ' ' << (a[i] + i - 1) / i << "\n";
        }
        for (int i = 2; i <= n; i++) {
            cout << 1 << ' ' << i << ' ' << sum / n << "\n";
        }
    }
    return 0;
}

 

posted @ 2020-09-28 15:00  Kanoon  阅读(369)  评论(0编辑  收藏  举报