11 .Codeforces Round 891 (Div. 3)E. Power of Points(推公式+前缀和优化)

E. Power of Points
image
题解参考

#include <bits/stdc++.h>

#define int long long
#define rep(i, a, b) for(int i = (a); i <= (b); ++i)
#define fep(i, a, b) for(int i = (a); i >= (b); --i)
#define _for(i, a, b) for(int i=(a); i<(b); ++i)
#define pii pair<int, int>
#define pdd pair<double,double>
#define ll long long
#define db double
#define x first
#define y second
#define pb push_back
#define vi vector<int>

using namespace std;
const int maxn = 1e5 + 10;

//int l[maxn],r[maxn],n;
struct node {
    int val, pos;

    bool operator<(const node &t) const {
        return val < t.val;
    }
};

void solve() {
    int n;
    cin >> n;
    vector<node> a(n + 1);
    vi l(n + 1), r(n + 2);
    rep(i, 1, n) {
        int k;
        cin >> k;
        a[i] = {k, i};
    }
    sort(a.begin() + 1, a.end());

    //预处理前缀和、后缀和
    rep(i, 1, n) {
        l[i] = l[i - 1] + a[i].val;
    }
    r[n] = a[n].val;
    fep(i, n - 1, 1) {
        r[i] = r[i + 1] + a[i].val;
    }

    vi ans(n + 1);
    rep(i, 1, n) {
        int res = n + (2 * i - n) * a[i].val - l[i] + r[i + 1];
        ans[a[i].pos] = res;
    }
    rep(i, 1, n) {
        cout << ans[i] << ' ';
    }
    cout << endl;
}

signed main() {

    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
//    freopen("C:\\Users\\24283\\CLionProjects\\untitled2\\1.in", "r", stdin);
    int _;
    cin >> _;
    while (_--)
        solve();
    return 0;
}

总结

  1. 注意下标
posted @ 2024-02-28 20:15  cxy8  阅读(1)  评论(0编辑  收藏  举报