CSES - Practice Contest 2024 - Results
Submission details
Task:Approximate
Sender:asdf
Submission time:2024-09-28 13:37:56 +0300
Language:C++ (C++20)
Status:READY
Result:ACCEPTED
Test results
testverdicttime
#1ACCEPTED0.24 sdetails

Code

#include <algorithm>
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define double long double

string to_string(string s) {
    return '"' + s + '"';
}
 
string to_string(const char* s) {
    return to_string((string) s);
}
 
string to_string(bool b) {
    return (b ? "true" : "false");
}
 
template <typename A, typename B>
string to_string(pair<A, B> p) {
    return "(" + to_string(p.first) + ", " + to_string(p.second) + ")";
}
 
template <typename A>
string to_string(A v) {
    bool first = true;
    string res = "{";
    for (const auto &x : v) {
        if (!first) {
            res += ", ";
        }
        first = false;
        res += to_string(x);
    }
    res += "}";
    return res;
}
 
void debug_out() {
    cerr << endl;
}
 
template <typename Head, typename... Tail>
void debug_out(Head H, Tail... T) {
    cerr << " " << to_string(H);
    debug_out(T...);
}
 
#ifdef LOCAL
#define debug(...) cerr << "[" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#else
#define debug(...) 42
#endif


const int N = 1e5 + 5;

int n, q;
int x[N], xx[N], p[N], pp[N];

void solve() {
    cin >> n >> q;
    for (int i = 1; i <= n; i++) {
        cin >> x[i];
        xx[i] = x[i] * x[i];
        p[i] = p[i - 1] + x[i];
        pp[i] = pp[i - 1] + xx[i];
    }

    while (q--) {
        int l, r;
        cin >> l >> r;

        int ss = pp[r] - pp[l - 1];
        int s = p[r] - p[l - 1];
        int len = r - l + 1;

        auto f = [&](double x) {
            return - 2 * s * x + len * x * x;
        };

        double low = 0, high = 100;
        for (int ite = 0; ite < 50; ite++) {
            // debug(low, high);
            double m1 = low + (high - low) / 3;
            double m2 = high - (high - low) / 3;
            double f1 = f(m1);
            double f2 = f(m2);
            if (f1 > f2)
                low = m1;
            else
                high = m2;
        }

        double x = low;
        double ans = (1.0 / len) * (ss - 2 * s * x + len * x * x);
        cout << fixed << setprecision(6) << ans << '\n';
    }
}

signed main() {
    cin.tie(0)->sync_with_stdio(0);

    int t;
    // cin >> t;
    t = 1;

    while (t--) {
        solve();
    }
}

Test details

Test 1

Verdict: ACCEPTED

input
100000 100000
62 64 35 47 57 38 52 4 56 13 7...

correct output
831.753342
833.361649
833.847478
834.425131
831.468120
...

user output
831.753342
833.361649
833.847478
834.425131
831.468120
...
Truncated