1 条题解

  • 0
    @ 2026-6-5 13:49:22

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

    typedef long long ll;

    int main() { ios::sync_with_stdio(false); cin.tie(nullptr);

    int n;
    cin >> n;
    
    set<int> s;
    ll ans = 0;
    
    for (int i = 1; i <= n; i++) {
        int x;
        cin >> x;
    
        if (i == 1) {
            ans += x;
        } else {
            int best = INT_MAX;
    
            auto it = s.lower_bound(x);
    
            // 后继
            if (it != s.end())
                best = min(best, *it - x);
    
            // 前驱
            if (it != s.begin()) {
                --it;
                best = min(best, x - *it);
            }
    
            ans += best;
        }
    
        s.insert(x);
    }
    
    cout << ans << '\n';
    return 0;
    

    }

    信息

    ID
    465
    时间
    1000ms
    内存
    512MiB
    难度
    6
    标签
    递交数
    24
    已通过
    10
    上传者