Problem:
H: 魔法使いの塔
問題文
あなたが持っている魔導書には、 $N$ 個の魔法が載っています。
魔法には $1$ から $N$ までの番号がついていて、魔法 $i (1 \le i \le N)$ のコストははじめ整数 $A_i$ です。
あなたの目的は、魔導書に載っているすべての魔法を $1$ 回ずつ唱えることです。
魔法を唱えはじめる前に、あなたはクッキーを $K$ 枚食べることができます。クッキーを食べるのに時間はかかりません。
あなたはクッキーを $1$ 枚食べるたびに、コストが正の魔法を $1$ つ選び、そのコストを $1$ 下げることができます。
クッキーを食べたあと、あなたは魔法を唱え始めます。
あなたの MP ははじめ $M$ です。あなたは以下のどちらかを繰り返して、 $N$ 個の魔法を任意の順番で $1$ 回ずつ唱えます。
整数 $i (1 \le i \le N)$ を $1$ つ選び、魔法 $i$ を唱える。ただし、 現在の MP は魔法 $i$ のコスト以上でなければならない。
時間は経過しない。
MP を魔法 $i$ のコストだけ消費する。
休憩する。ただし、現在の MP を $m$ とすると、 $m < M$ でなければならない。
時間が $M - m$ 経過する。
MP を $1$ 回復する。
あなたが $N$ 個の魔法を任意の順番で $1$ 回ずつ唱えるためにかかる時間の最小値を求めてください。
制約
$1 \leq N \leq 10^5$
$1 \leq M \leq 10^6$
$0 \leq K \leq \sum_{i=1}^{N} A_i$
$1 \leq A_i \leq M$
入力はすべて整数である。
入力
入力は以下の形式で標準入力から与えられる。
$N$ $M$ $K$
$A_1$ $A_2$ $\ldots$ $A_N$
出力
$N$ 個の魔法を $1$ 回ずつ唱えるためにかかる時間の最小値を出力せよ。
入力例1
2 4 0
2 4
出力例1
3
どの魔法のコストも減らすことができないので、このまま魔法を唱えていくことにします。
まず、魔法 $1$ を唱えます。 MP を $2$ 消費するので、残りの MP は $4 - 2 = 2$ になります。
魔法 $2$ を唱えるには MP が $4$ 必要なので、このままでは魔法 $2$ を唱えることはできません。
休憩します。時間が $4 - 2 = 2$ 秒経過します。 MP を $1$ 回復するので、残りの MP は $2 + 1 = 3$ になります。
休憩します。時間が $4 - 3 = 1$ 秒経過します。 MP を $1$ 回復するので、残りの MP は $3 + 1 = 4$ になります。
魔法 $2$ を唱えます。 MP を $4$ 消費するので、残りの MP は $4 - 4 = 0$ になります。
以上より、時間を $2 + 1 = 3$ 秒かければ、魔法 $1,2$ を $1$ 回ずつ唱えることができます。
これより短い時間ですべての魔法を唱えることはできないので、求める答えは $3$ となります。
入力例2
3 9 6
2 3 9
出力例2
0
最終的な魔法のコストを $2, 2, 4$ とすると、休憩することなくすべての魔法を唱えることができます。
入力例3
3 16 2
6 9 9
出力例3
21
入力例4
2 1000000 0
1000000 1000000
出力例4
500000500000
答えは 32bit 整数で表せる範囲に収まらないことがあります。

Submitted solutions:

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll=int64_t;

int main(){
  int n;
  ll M,k;
  cin >> n >> M >> k;

  vector<ll> a(n+1);
  vector<ll> as(n+1,0);
  ll asum=0;
  
  for(int i=1;i<=n;i++){
    cin >> a[i];
    asum+=a[i];
  }
  if((n==1)||(M>=asum-k)){
    cout << 0 << endl;
    return 0;
  }

  sort(a.begin(),a.end());
  for(int i=1;i<=n;i++) as[i]=as[i-1]+a[i];
  
  ll as1=0,asd;
  int cc=n;
  while(as1+a[cc]<=M){
    as1+=a[cc];
    a.pop_back();
    cc--;
  }
  asd=M-as1;
  //cout << asd <<" " << cc << endl;
  
  int im2;

  if(k>0){
    ll lw=0,hi=M+1;
    int im;
    ll sum1,sum2;
    while(hi-lw>1){
      ll mid=(lw+hi)/2;
      im=distance(a.begin(),lower_bound(a.begin(),a.end(),mid));
      //cout << mid << " " << im << endl;
      if(im==cc+1){
        hi=mid;
        continue;
      }
      sum1=(as[cc]-as[im-1])-(mid-1)*(cc-im+1)-((mid-1)>=asd ? 0 :asd-(mid-1));
      if(k>=sum1) hi=mid;
      else lw=mid;
      //cout << mid << " " << im << " " << sum1 << endl;
    }
    im2=distance(a.begin(),lower_bound(a.begin(),a.end(),hi));
    sum2=(as[cc]-as[im2-1])-(hi-1)*(cc-im2+1)-((hi-1)>=asd ? 0 :asd-(hi-1));
    //cout << hi << " " << im2 << " " << k-sum2 << endl;
    
    for(int i=im2;i<cc;i++) a[i]=hi-1;
    (hi-1)>asd ? a[cc]=hi-1 : a[cc]=asd;
    
    ll dd=k-sum2;
    int ci=cc;
    while(dd>0){
      if(ci==cc){
        if(a[ci]>asd){
          dd--;
          a[ci]--;
        }
      }else{
        dd--;
        a[ci]--;
      }
      ci--;
    }
  
  }
  
  ll ans=0;
  for(int i=1;i<=cc;i++){
    ans+=(a[i]+1)*a[i]/2;
  }
  ans-=(asd+1)*asd/2;
  cout << ans << endl;
}
accuracy: 1
time_ms: 20
memory_kb: 4688
final_rank: 13

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll=int64_t;

int main(){
  int n;
  ll M,k;
  cin >> n >> M >> k;

  vector<int> a(n+1);
  vector<ll> as(n+1,0);
  ll asum=0;
  
  for(int i=1;i<=n;i++){
    cin >> a[i];
    asum+=a[i];
  }
  if((n==1)||(M>=asum-k)){
    cout << 0 << endl;
    return 0;
  }

  sort(a.begin(),a.end());
  for(int i=1;i<=n;i++) as[i]=as[i-1]+a[i];
  
  ll as1=0,asd;
  int cc=n;
  while(as1+a[cc]<=M){
    as1+=a[cc];
    a.pop_back();
    cc--;
  }
  asd=M-as1;
  //cout << asd <<" " << cc << endl;
  
  int im2;
  ll ans=0,d;

  if(k>0){
    int lw=0,hi=M+1,im;
    ll sum1,sum2;
    while(hi-lw>1){
      int mid=(lw+hi)/2;
      im=distance(a.begin(),lower_bound(a.begin(),a.end(),mid));
      //cout << mid << " " << im << endl;
      if(im==cc+1){
        hi=mid;
        continue;
      }
      sum1=(as[cc]-as[im-1])-(mid-1)*(cc-im+1)-((mid-1)>=asd ? 0 :asd-(mid-1));
      if(k>=sum1) hi=mid;
      else lw=mid;
      //cout << mid << " " << im << " " << sum1 << endl;
    }
    im2=distance(a.begin(),lower_bound(a.begin(),a.end(),hi));
    sum2=(as[cc]-as[im2-1])-(hi-1)*(cc-im2+1)-((hi-1)>=asd ? 0 :asd-(hi-1));
    //cout << hi << " " << im2 << " " << k-sum2 << endl;
    
    for(int i=im2;i<cc;i++) a[i]=hi-1;
    (hi-1)>asd ? a[cc]=hi-1 : a[cc]=asd;
    
    ll dd=k-sum2;
    int ci=cc;
    while(dd>0){
      if(ci==cc){
        if(a[ci]>asd){
          dd--;
          a[ci]--;
        }
      }else{
        dd--;
        a[ci]--;
      }
      ci--;
    }
  
  }
  for(int i=1;i<=cc;i++){
    ans+=((ll)a[i]+1)*a[i]/2;
  }
  ans-=(asd+1)*asd/2;
  cout << ans << endl;
}
accuracy: 0.6818181818181818
time_ms: 10
memory_kb: 3536
final_rank: 19

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll=int64_t;

int main(){
  int n;
  ll M,k;
  cin >> n >> M >> k;

  vector<int> a(n+1);
  vector<ll> as(n+1,0);
  ll asum=0;
  
  for(int i=1;i<=n;i++){
    cin >> a[i];
    asum+=a[i];
  }
  if((n==1)||(M>=asum-k)){
    cout << 0 << endl;
    return 0;
  }

  sort(a.begin(),a.end());
  for(int i=1;i<=n;i++) as[i]=as[i-1]+a[i];
  
  ll as1=0,asd;
  int cc=n;
  while(as1+a[cc]<=M){
    as1+=a[cc];
    a.pop_back();
    cc--;
  }
  asd=M-as1;
  //cout << asd <<" " << cc << endl;
  
  int abb,im2;
  ll ans=0,d;

  if(k==0){
    abb=a[cc];
    im2=cc;
    
  }else{
  
    int lw=0,hi=M+1,im;
    ll sum1,sum2;
    while(hi-lw>1){
      int mid=(lw+hi)/2;
      im=distance(a.begin(),lower_bound(a.begin(),a.end(),mid));
      //cout << mid << " " << im << endl;
      if(im==cc+1){
        hi=mid;
        continue;
      }
      sum1=(as[cc]-as[im-1])-a[im-1]*(cc-im+1)-(a[im-1]>=asd ? 0 :asd-a[im-1]);
      if(k>sum1) hi=mid;
      else lw=mid;
      //cout << mid << " " << im << " " << sum1 << endl;
    }
    im2=distance(a.begin(),lower_bound(a.begin(),a.end(),lw));
    sum2=(as[cc]-as[im2-1])-a[im2-1]*(cc-im2+1)-(a[im2-1]>=asd ? 0 :asd-a[im2-1]);
    //cout << (as[cc]-as[im2-1]) << " " << a[im2-1]*(cc-im2+1) << " " << (a[im2-1]>=asd ? 0 :asd-a[im2-1]) << endl;
    //cout << lw << " " << im2 << " " << sum2 << endl;
    
    ll dd=sum2-k;
    int cd=cc-im2+1,df=int(dd/cd),ccd;
    //cout << dd << " " << df << " " << cd << endl;
    int dfc1,dfc2;
    if(cd==1){
      abb=max((int)asd,a[im2-1])+df;
      dfc1=0;
      dfc2=0;
    }else if(asd<=a[im2-1]){
      ccd=int(dd-cd*df);
      abb=(ccd==0 ? a[im2-1]+df : a[im2-1]+df+1);
      if(ccd==0){
        dfc1=0;
        dfc2=cd-1;
      }else{
        dfc1=ccd-1;
        dfc2=cd-ccd;
      }
    }else if(dd==0){
      abb=max((int)asd,a[im2-1]);
      dfc1=0;
      dfc2=cd-1;
    }else{
      if((dd/(cd-1))+a[im2-1]<=asd){
        df=dd/(cd-1);
        ccd=int(dd-df*(cd-1));
        dfc1=ccd;
        dfc2=cd-1-ccd;
        abb=asd;
      }else{
        int df1=asd-a[im2-1];
        df=df1+(dd-df1*(cd-1))/cd;
        ccd=int(dd-df1*(cd-1))%cd;
        abb=(ccd==0 ? a[im2-1]+df : a[im2-1]+df+1);
        if(ccd==0){
          dfc1=0;
          dfc2=cd-1;
        }else{
          dfc1=ccd-1;
          dfc2=cd-ccd;
        }

      }
    }
   //cout << a[im2-1] << " " << dd << " " << df << " " << cd << " " << ccd << " " << abb << endl;
  
    if(im2<cc){
      d=a[im2-1]+df+1;
      if(d%2){
        ans+=(d+d*((d-1)/2))*dfc1;
      }else{
        ans+=(d+1)*(d/2)*dfc1;
      }
      d=a[im2-1]+df;
      if(d%2){
        ans+=(d+d*((d-1)/2))*dfc2;
      }else{
        ans+=(d+1)*(d/2)*dfc2;
      }
    }
  }
  //cout << abb << " " << asd << " " << im2 << endl;
  d=abb;
  if(d%2){
    ans+=d+d*((d-1)/2);
  }else{
    ans+=(d+1)*(d/2);
  }
  d=asd;
  if(d%2){
    ans-=d+d*((d-1)/2);
  }else{
    ans-=(d+1)*(d/2);
  }
  


  for(int i=1;i<im2;i++){
    d=a[i];
    //cout << ans << " " << d << endl;
    if(d%2){
      ans+=d+d*((d-1)/2);
    }else{
      ans+=(d+1)*(d/2);
    }
  }
  cout << ans << endl;
}
accuracy: 0.6818181818181818
time_ms: 20
memory_kb: 4132
final_rank: 20

code_snippet: //#define _GLIBCXX_DEBUG

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

#define endl '\n'
#define lfs cout<<fixed<<setprecision(10)
#define ALL(a)  (a).begin(),(a).end()
#define ALLR(a)  (a).rbegin(),(a).rend()
#define spa << " " <<
#define fi first
#define se second
#define MP make_pair
#define MT make_tuple
#define PB push_back
#define EB emplace_back
#define rep(i,n,m) for(ll i = (n); i < (ll)(m); i++)
#define rrep(i,n,m) for(ll i = (ll)(m) - 1; i >= (ll)(n); i--)
using ll = long long;
using ld = long double;
const ll MOD1 = 1e9+7;
const ll MOD9 = 998244353;
const ll INF = 1e18;
using P = pair<ll, ll>;
template<typename T> using PQ = priority_queue<T>;
template<typename T> using QP = priority_queue<T,vector<T>,greater<T>>;
template<typename T1, typename T2>bool chmin(T1 &a,T2 b){if(a>b){a=b;return true;}else return false;}
template<typename T1, typename T2>bool chmax(T1 &a,T2 b){if(a<b){a=b;return true;}else return false;}
ll median(ll a,ll b, ll c){return a+b+c-max({a,b,c})-min({a,b,c});}
void ans1(bool x){if(x) cout<<"Yes"<<endl;else cout<<"No"<<endl;}
void ans2(bool x){if(x) cout<<"YES"<<endl;else cout<<"NO"<<endl;}
void ans3(bool x){if(x) cout<<"Yay!"<<endl;else cout<<":("<<endl;}
template<typename T1,typename T2>void ans(bool x,T1 y,T2 z){if(x)cout<<y<<endl;else cout<<z<<endl;}  
template<typename T1,typename T2,typename T3>void anss(T1 x,T2 y,T3 z){ans(x!=y,x,z);};  
template<typename T>void debug(const T &v,ll h,ll w,string sv=" "){for(ll i=0;i<h;i++){cout<<v[i][0];for(ll j=1;j<w;j++)cout<<sv<<v[i][j];cout<<endl;}};
template<typename T>void debug(const T &v,ll n,string sv=" "){if(n!=0)cout<<v[0];for(ll i=1;i<n;i++)cout<<sv<<v[i];cout<<endl;};
template<typename T>void debug(const vector<T>&v){debug(v,v.size());}
template<typename T>void debug(const vector<vector<T>>&v){for(auto &vv:v)debug(vv,vv.size());}
template<typename T>void debug(stack<T> st){while(!st.empty()){cout<<st.top()<<" ";st.pop();}cout<<endl;}
template<typename T>void debug(queue<T> st){while(!st.empty()){cout<<st.front()<<" ";st.pop();}cout<<endl;}
template<typename T>void debug(deque<T> st){while(!st.empty()){cout<<st.front()<<" ";st.pop_front();}cout<<endl;}
template<typename T>void debug(PQ<T> st){while(!st.empty()){cout<<st.top()<<" ";st.pop();}cout<<endl;}
template<typename T>void debug(QP<T> st){while(!st.empty()){cout<<st.top()<<" ";st.pop();}cout<<endl;}
template<typename T>void debug(const set<T>&v){for(auto z:v)cout<<z<<" ";cout<<endl;}
template<typename T>void debug(const multiset<T>&v){for(auto z:v)cout<<z<<" ";cout<<endl;}
template<typename T,size_t size>void debug(const array<T, size> &a){for(auto z:a)cout<<z<<" ";cout<<endl;}
template<typename T,typename V>void debug(const map<T,V>&v){for(auto z:v)cout<<"["<<z.first<<"]="<<z.second<<",";cout<<endl;}
template<typename T>vector<vector<T>>vec(ll x, ll y, T w){vector<vector<T>>v(x,vector<T>(y,w));return v;}
ll gcd(ll x,ll y){ll r;while(y!=0&&(r=x%y)!=0){x=y;y=r;}return y==0?x:y;}
vector<ll>dx={1,-1,0,0,1,1,-1,-1};vector<ll>dy={0,0,1,-1,1,-1,1,-1};
template<typename T>vector<T> make_v(size_t a,T b){return vector<T>(a,b);}
template<typename... Ts>auto make_v(size_t a,Ts... ts){return vector<decltype(make_v(ts...))>(a,make_v(ts...));}
template<typename T1, typename T2>ostream &operator<<(ostream &os, const pair<T1, T2>&p){return os << p.first << " " << p.second;}
template<typename T>ostream &operator<<(ostream &os, const vector<T> &v){for(auto &z:v)os << z << " ";cout<<"|"; return os;}
template<typename T>void rearrange(vector<int>&ord, vector<T>&v){
  auto tmp = v;
  for(int i=0;i<tmp.size();i++)v[i] = tmp[ord[i]];
}
template<typename Head, typename... Tail>void rearrange(vector<int>&ord,Head&& head, Tail&&... tail){
  rearrange(ord, head);
  rearrange(ord, tail...);
}
template<typename T> vector<int> ascend(const vector<T>&v){
  vector<int>ord(v.size());iota(ord.begin(),ord.end(),0);
  sort(ord.begin(),ord.end(),[&](int i,int j){return v[i]<v[j];});
  return ord;
}
template<typename T> vector<int> descend(const vector<T>&v){
  vector<int>ord(v.size());iota(ord.begin(),ord.end(),0);
  sort(ord.begin(),ord.end(),[&](int i,int j){return v[i]>v[j];});
  return ord;
}
ll FLOOR(ll n,ll div){return n>=0?n/div:(n-div+1)/div;}
ll CEIL(ll n,ll div){return n>=0?(n+div-1)/div:n/div;}
ll digitsum(ll n){ll ret=0;while(n){ret+=n%10;n/=10;}return ret;}
template<typename T>T min(const vector<T>&v){return *min_element(v.begin(),v.end());}
template<typename T>T max(const vector<T>&v){return *max_element(v.begin(),v.end());}
template<typename T>T acc(const vector<T>&v){return accumulate(v.begin(),v.end(),T(0));};
template<typename T>T reverse(const T &v){return T(v.rbegin(),v.rend());};
//mt19937 mt(chrono::steady_clock::now().time_since_epoch().count());
int popcount(ll x){return __builtin_popcountll(x);};
int poplow(ll x){return __builtin_ctzll(x);};
int pophigh(ll x){return 63 - __builtin_clzll(x);};
template<typename T>T poll(queue<T> &q){auto ret=q.front();q.pop();return ret;};
template<typename T>T poll(priority_queue<T> &q){auto ret=q.top();q.pop();return ret;};
template<typename T>T poll(QP<T> &q){auto ret=q.top();q.pop();return ret;};
template<typename T>T poll(stack<T> &s){auto ret=s.top();s.pop();return ret;};
template< typename T = int >
struct edge {
  int to;
  T cost;
  int id;
  edge():id(-1){};
  edge(int to, T cost = 1, int id = -1):to(to), cost(cost), id(id){}
  operator int() const { return to; }
};

template<typename T>
using Graph = vector<vector<edge<T>>>;
template<typename T>
Graph<T>revgraph(const Graph<T> &g){
  Graph<T>ret(g.size());
  for(int i=0;i<g.size();i++){
    for(auto e:g[i]){
      int to = e.to;
      e.to = i;
      ret[to].push_back(e);
    }
  }
  return ret;
}
template<typename T>
Graph<T> readGraph(int n,int m,int indexed=1,bool directed=false,bool weighted=false){
  Graph<T> ret(n);
  for(int es = 0; es < m; es++){
    int u,v;
    T w=1;
    cin>>u>>v;u-=indexed,v-=indexed;
    if(weighted)cin>>w;
    ret[u].emplace_back(v,w,es);
    if(!directed)ret[v].emplace_back(u,w,es);
  }
  return ret;
}
template<typename T>
Graph<T> readParent(int n,int indexed=1,bool directed=true){
  Graph<T>ret(n);
  for(int i=1;i<n;i++){
    int p;cin>>p;
    p-=indexed;
    ret[p].emplace_back(i);
    if(!directed)ret[i].emplace_back(p);
  }
  return ret;
}

int main(){
  cin.tie(nullptr);
  ios_base::sync_with_stdio(false);
  ll res=0,buf=0;
  bool judge = true;
  ll n,m,k;cin>>n>>m>>k;
  vector<ll>a(n);
  rep(i,0,n)cin>>a[i];
  res=0;
  rep(i,0,n)res+=a[i]*(a[i]+1)/2;
  sort(ALLR(a));
  vector<ll>l(n),r(n);
  rep(i,0,n){
    l[i]=0,r[i]=a[i];
    ll mi=min(a[i],m);
    res-=mi*(mi+1)/2;
    l[i]+=mi;
    m-=mi;
  }
  //cout<<res spa m<<endl;
  //debug(l);debug(r);
  ll cost=0,rk;
  auto f=[&](ll lower){
    rk=k,cost=0;
    rrep(i,0,n){
      ll mi=min(rk,max(0LL,r[i]-max(lower,l[i])));
      rk-=mi;
      cost+=r[i]*(r[i]+1)/2-(r[i]-mi)*(r[i]-mi+1)/2;
    }
    //cout<<lower spa cost spa rk<<endl;
  };
  ll ng=-1,ok=10000000;
  while(abs(ok-ng)>=2){
    ll mid=(ok+ng)/2;
    f(mid);
    if(rk>0)ok=mid;
    else ng=mid;
  }
  f(ok);
  cout<<res-cost-ok*rk<<endl;
  return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 5428
final_rank: 5

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

using ll=long long;
#define int ll

#define rng(i,a,b) for(int i=int(a);i<int(b);i++)
#define rep(i,b) rng(i,0,b)
#define gnr(i,a,b) for(int i=int(b)-1;i>=int(a);i--)
#define per(i,b) gnr(i,0,b)
#define pb push_back
#define eb emplace_back
#define a first
#define b second
#define bg begin()
#define ed end()
#define all(x) x.bg,x.ed
#define si(x) int(x.size())
#ifdef LOCAL
#define dmp(x) cerr<<__LINE__<<" "<<#x<<" "<<x<<endl
#else
#define dmp(x) void(0)
#endif

template<class t,class u> void chmax(t&a,u b){if(a<b)a=b;}
template<class t,class u> void chmin(t&a,u b){if(b<a)a=b;}

template<class t> using vc=vector<t>;
template<class t> using vvc=vc<vc<t>>;

using pi=pair<int,int>;
using vi=vc<int>;

template<class t,class u>
ostream& operator<<(ostream& os,const pair<t,u>& p){
	return os<<"{"<<p.a<<","<<p.b<<"}";
}

template<class t> ostream& operator<<(ostream& os,const vc<t>& v){
	os<<"{";
	for(auto e:v)os<<e<<",";
	return os<<"}";
}

#define mp make_pair
#define mt make_tuple
#define one(x) memset(x,-1,sizeof(x))
#define zero(x) memset(x,0,sizeof(x))
#ifdef LOCAL
void dmpr(ostream&os){os<<endl;}
template<class T,class... Args>
void dmpr(ostream&os,const T&t,const Args&... args){
	os<<t<<" ";
	dmpr(os,args...);
}
#define dmp2(...) dmpr(cerr,__LINE__,##__VA_ARGS__)
#else
#define dmp2(...) void(0)
#endif

using uint=unsigned;
using ull=unsigned long long;

template<class t,size_t n>
ostream& operator<<(ostream&os,const array<t,n>&a){
	return os<<vc<t>(all(a));
}

template<int i,class T>
void print_tuple(ostream&,const T&){
}

template<int i,class T,class H,class ...Args>
void print_tuple(ostream&os,const T&t){
	if(i)os<<",";
	os<<get<i>(t);
	print_tuple<i+1,T,Args...>(os,t);
}

template<class ...Args>
ostream& operator<<(ostream&os,const tuple<Args...>&t){
	os<<"{";
	print_tuple<0,tuple<Args...>,Args...>(os,t);
	return os<<"}";
}

template<class t>
void print(t x,int suc=1){
	cout<<x;
	if(suc==1)
		cout<<"\n";
	if(suc==2)
		cout<<" ";
}

ll read(){
	ll i;
	cin>>i;
	return i;
}

vi readvi(int n,int off=0){
	vi v(n);
	rep(i,n)v[i]=read()+off;
	return v;
}

pi readpi(int off=0){
	int a,b;cin>>a>>b;
	return pi(a+off,b+off);
}

template<class T>
void print(const vector<T>&v,int suc=1){
	rep(i,v.size())
		print(v[i],i==int(v.size())-1?suc:2);
}

string readString(){
	string s;
	cin>>s;
	return s;
}

template<class T>
T sq(const T& t){
	return t*t;
}

//#define CAPITAL
void yes(bool ex=true){
	#ifdef CAPITAL
	cout<<"YES"<<"\n";
	#else
	cout<<"Yes"<<"\n";
	#endif
	if(ex)exit(0);
	#ifdef LOCAL
	cout.flush();
	#endif
}
void no(bool ex=true){
	#ifdef CAPITAL
	cout<<"NO"<<"\n";
	#else
	cout<<"No"<<"\n";
	#endif
	if(ex)exit(0);
	#ifdef LOCAL
	cout.flush();
	#endif
}
void possible(bool ex=true){
	#ifdef CAPITAL
	cout<<"POSSIBLE"<<"\n";
	#else
	cout<<"Possible"<<"\n";
	#endif
	if(ex)exit(0);
	#ifdef LOCAL
	cout.flush();
	#endif
}
void impossible(bool ex=true){
	#ifdef CAPITAL
	cout<<"IMPOSSIBLE"<<"\n";
	#else
	cout<<"Impossible"<<"\n";
	#endif
	if(ex)exit(0);
	#ifdef LOCAL
	cout.flush();
	#endif
}

constexpr ll ten(int n){
	return n==0?1:ten(n-1)*10;
}

const ll infLL=LLONG_MAX/3;

#ifdef int
const int inf=infLL;
#else
const int inf=INT_MAX/2-100;
#endif

int topbit(signed t){
	return t==0?-1:31-__builtin_clz(t);
}
int topbit(ll t){
	return t==0?-1:63-__builtin_clzll(t);
}
int botbit(signed a){
	return a==0?32:__builtin_ctz(a);
}
int botbit(ll a){
	return a==0?64:__builtin_ctzll(a);
}
int popcount(signed t){
	return __builtin_popcount(t);
}
int popcount(ll t){
	return __builtin_popcountll(t);
}
bool ispow2(int i){
	return i&&(i&-i)==i;
}
ll mask(int i){
	return (ll(1)<<i)-1;
}

bool inc(int a,int b,int c){
	return a<=b&&b<=c;
}

template<class t> void mkuni(vc<t>&v){
	sort(all(v));
	v.erase(unique(all(v)),v.ed);
}

ll rand_int(ll l, ll r) { //[l, r]
	#ifdef LOCAL
	static mt19937_64 gen;
	#else
	static mt19937_64 gen(chrono::steady_clock::now().time_since_epoch().count());
	#endif
	return uniform_int_distribution<ll>(l, r)(gen);
}

template<class t>
void myshuffle(vc<t>&a){
	rep(i,si(a))swap(a[i],a[rand_int(0,i)]);
}

template<class t>
int lwb(const vc<t>&v,const t&a){
	return lower_bound(all(v),a)-v.bg;
}

vvc<int> readGraph(int n,int m){
	vvc<int> g(n);
	rep(i,m){
		int a,b;
		cin>>a>>b;
		//sc.read(a,b);
		a--;b--;
		g[a].pb(b);
		g[b].pb(a);
	}
	return g;
}

vvc<int> readTree(int n){
	return readGraph(n,n-1);
}

signed main(){
	cin.tie(0);
	ios::sync_with_stdio(0);
	cout<<fixed<<setprecision(20);
	
	int n,m,k;cin>>n>>m>>k;
	vi a=readvi(n);
	sort(all(a),greater<int>());
	int cur=0;
	vi sum(m+1);
	for(auto v:a){
		if(cur+v<=m){
			cur+=v;
		}else{
			sum[cur]--;
			cur=m-v;
			sum[cur]++;
			cur+=v;
		}
	}
	int ans=0;
	rep(i,m)sum[i+1]+=sum[i];
	rep(i,m){
		int u=min(k,sum[i]);
		k-=u;
		sum[i]-=u;
		ans+=(m-i)*sum[i];
	}
	print(ans);
}
accuracy: 1
time_ms: 10
memory_kb: 11416
final_rank: 14

code_snippet: #include <iostream>
#include <utility>
#include <tuple>
#include <vector>
#include <string>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <algorithm>
#include <functional>
#include <climits>
#include <numeric>
#include <queue>
#include <cmath>
#include <iomanip>
#include <array>
#include <string>
#include <stack>
#include <cassert>
#include <memory>
long long int recover_all(int a) {
	return a * (a + 1LL) / 2;
}
int main() {
	int n, m; long long int k; std::cin >> n >> m >> k;
	std::vector<int> magic(n); for (auto& a : magic) std::cin >> a;
	std::sort(magic.begin(), magic.end());
	const auto need_to_recover = std::accumulate(magic.begin(), magic.end(), 0LL) - m;
	if (need_to_recover <= 0) {
		std::cout << 0 << '\n'; return 0;
	}
	int min{ 0 }, max{ m };
	while (min < max) {
		const auto mid = (min + max) >> 1;
		auto cookie = k;
		auto recover = need_to_recover;
		for (auto a : magic) {
			if (cookie < 0) break;
			if (mid < a) {
				const auto minus = std::min<long long int>(a - mid, recover);
				cookie -= minus;
				recover -= minus;
				a -= minus;
			}
			recover -= std::min<long long int>(recover, a);
		}
		if (cookie < 0) {
			min = mid + 1;
		}
		else {
			max = mid;
		}
	}
	auto cookie = k;
	auto recover = need_to_recover;
	long long int time{ 0 };
	int just{ 0 };
	for (auto a : magic) {
		if (max < a) {
			const auto minus = std::min<long long int>(a - max, recover);
			cookie -= minus;
			recover -= minus;
			a -= minus;
		}
		const auto r = std::min<long long int>(recover, a);
		time += recover_all(a) - recover_all(a - r);
		recover -= r;
		if (a == max) ++just;
	}
	const auto additional = std::min<long long int>(just, cookie);
	time -= max * additional;
	std::cout << time << '\n';
}
accuracy: 1
time_ms: 20
memory_kb: 3264
final_rank: 7

code_snippet: #include <iostream>
#include <utility>
#include <tuple>
#include <vector>
#include <string>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <algorithm>
#include <functional>
#include <climits>
#include <numeric>
#include <queue>
#include <cmath>
#include <iomanip>
#include <array>
#include <string>
#include <stack>
#include <cassert>
#include <memory>
long long int recover_all(int a) {
	return a * (a + 1LL) / 2;
}
int main() {
	int n, m, k; std::cin >> n >> m >> k;
	std::vector<int> magic(n); for (auto& a : magic) std::cin >> a;
	std::sort(magic.begin(), magic.end());
	const auto need_to_recover = std::accumulate(magic.begin(), magic.end(), 0LL) - m;
	if (need_to_recover <= 0) {
		std::cout << 0 << '\n'; return 0;
	}
	int min{ 0 }, max{ m };
	while (min < max) {
		const auto mid = (min + max) >> 1;
		auto cookie = k;
		auto recover = need_to_recover;
		for (auto a : magic) {
			if (cookie < 0) break;
			if (mid < a) {
				const auto minus = std::min<long long int>(a - mid, recover);
				cookie -= minus;
				recover -= minus;
				a -= minus;
			}
			recover -= std::min<long long int>(recover, a);
		}
		if (cookie < 0) {
			min = mid + 1;
		}
		else {
			max = mid;
		}
	}
	auto cookie = k;
	auto recover = need_to_recover;
	long long int time{ 0 };
	int just{ 0 };
	for (auto a : magic) {
		if (max < a) {
			const auto minus = std::min<long long int>(a - max, recover);
			cookie -= minus;
			recover -= minus;
			a -= minus;
		}
		const auto r = std::min<long long int>(recover, a);
		time += recover_all(a) - recover_all(a - r);
		recover -= r;
		if (a == max) ++just;
	}
	const auto additional = std::min(just, cookie);
	time -= (long long int)max * additional;
	std::cout << time << '\n';
}
accuracy: 0.6931818181818182
time_ms: 20
memory_kb: 3264
final_rank: 18

code_snippet: #include <bits/stdc++.h>
using namespace std;
#define rep(i,a,n) for (int i=a;i<n;i++)
#define per(i,a,n) for (int i=n-1;i>=a;i--)
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
typedef vector<int> VI;
typedef long long ll;
typedef pair<int,int> PII;
typedef double db;
mt19937 mrand(1); 
const ll mod=998244353;
int rnd(int x) { return mrand() % x;}
ll powmod(ll a,ll b) {ll res=1;a%=mod; assert(b>=0); for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;}
ll gcd(ll a,ll b) { return b?gcd(b,a%b):a;}
// head

const int N=101000;
#define kill assss
int n,m,a[N],kill[N];
ll k,rm,ans;
int main() {
	scanf("%d%d%lld",&n,&m,&k);
	rep(i,0,n) scanf("%d",a+i);
	sort(a,a+n);
	rep(i,0,n) rm+=a[i];
	rep(i,0,n) {
		if (rm<=m) break;
		if (rm-a[i]>m) kill[i]=a[i];
		else {
			int l=a[i],r=m-(rm-a[i]);
			kill[i]=l-r;
		}
		rm-=a[i];
	}

	int l=-1,r=m;
	while (l+1<r) {
		int md=(l+r)>>1;
		ll s=0;
		rep(i,0,n) s+=min(max(a[i]-md,0),kill[i]);
		if (s<=k) r=md; else l=md;
	}
	rep(i,0,n) {
		int d=min(max(a[i]-r,0),kill[i]);
		k-=d;
		a[i]-=d;
		kill[i]-=d;
	}
	rep(i,0,n) if (k&&a[i]==r&&kill[i]) --k,--a[i],--kill[i];
	/*rep(i,0,n) printf("%d ",a[i]); 
	puts("");*/
	sort(a,a+n);
	rm=0;
	rep(i,0,n) rm+=a[i];
	rep(i,0,n) {
		if (rm<=m) break;
		if (rm-a[i]>m) ans+=(ll)a[i]*(a[i]+1)/2;
		else {
			int l=a[i],r=m-(rm-a[i])+1;
		//	printf("%d %d\n",l,r);
			ans+=(ll)(l+r)*(l-r+1)/2;
		}
		rm-=a[i];
	}
	printf("%lld\n",ans);
}
accuracy: 1
time_ms: 10
memory_kb: 4040
final_rank: 3

code_snippet: #include <bits/stdc++.h>
using namespace std;
/*#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template<typename T> using gpp_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template<typename T, typename L> using gpp_map = tree<T, L, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template<typename T> using gpp_multiset = tree<T, null_type, less_equal<T>, rb_tree_tag, tree_order_statistics_node_update>;*/
struct fast_ios { fast_ios(){ cin.tie(0); ios::sync_with_stdio(false); cout << fixed << setprecision(20); }; } fast_ios_;
#define FOR(i, begin, end) for(int i=(begin);i<(end);i++)
#define REP(i, n) FOR(i,0,n)
#define IFOR(i, begin, end) for(int i=(end)-1;i>=(begin);i--)
#define IREP(i, n) IFOR(i,0,n)
#define Sort(v) sort(v.begin(), v.end())
#define Reverse(v) reverse(v.begin(), v.end())
#define all(v) v.begin(),v.end()
#define SZ(v) ((int)v.size())
#define Lower_bound(v, x) distance(v.begin(), lower_bound(v.begin(), v.end(), x))
#define Upper_bound(v, x) distance(v.begin(), upper_bound(v.begin(), v.end(), x))
#define Max(a, b) a = max(a, b)
#define Min(a, b) a = min(a, b)
#define bit(n) (1LL<<(n))
#define bit_exist(x, n) ((x >> n) & 1)
#define debug(x) cout << #x << "=" << x << endl;
#define vdebug(v) { cout << #v << "=" << endl; REP(i_debug, v.size()){ cout << v[i_debug] << ","; } cout << endl; }
#define mdebug(m) { cout << #m << "=" << endl; REP(i_debug, m.size()){ REP(j_debug, m[i_debug].size()){ cout << m[i_debug][j_debug] << ","; } cout << endl;} }
#define Return(ans) { cout << (ans) << endl; return 0; }
#define pb push_back
#define f first
#define s second
#define int long long
#define INF 1000000000000000000
template<typename T> istream &operator>>(istream &is, vector<T> &v){ for (auto &x : v) is >> x; return is; }
template<typename T> ostream &operator<<(ostream &os, vector<T> &v){ for(int i = 0; i < v.size(); i++) { cout << v[i]; if(i != v.size() - 1) cout << endl; }; return os; }
template<typename T1, typename T2> ostream &operator<<(ostream &os, pair<T1, T2> p){ cout << '(' << p.first << ',' << p.second << ')'; return os; }
template<typename T> void Out(T x) { cout << x << endl; }
template<typename T1, typename T2> void Ans(bool f, T1 y, T2 n) { if(f) Out(y); else Out(n); }

using vec = vector<int>;
using mat = vector<vec>;
using Pii = pair<int, int>;
using PiP = pair<int, Pii>;
using PPi = pair<Pii, int>;
using bools = vector<bool>;
using pairs = vector<Pii>;

//int dx[4] = {1,0,-1,0};
//int dy[4] = {0,1,0,-1};
//char d[4] = {'D','R','U','L'};

const int mod = 1000000007;
//const int mod = 998244353;
//#define Add(x, y) x = (x + (y)) % mod
//#define Mult(x, y) x = (x * (y)) % mod

int solve(vec A, int N, int M, int K, int r){

    int x0 = 0, x1 = M;
    while(x1 - x0 > 1){
        int x = (x0 + x1) / 2;
        int cnt = 0;
        REP(i, N) if(A[i] > x) cnt += A[i] - x;

        if(cnt <= K) x1 = x;
        else x0 = x;
    }

    int cnt = 0;
    REP(i, N) if(A[i] > x1){
        cnt += A[i] - x1;
        A[i] = x1;
    }
    REP(i, N) if(A[i] == A[N - 1] && cnt < K){
        cnt++;
        A[i]--;
    }

    if(A[N - 1] < r) return INF;

    int t = 0;
    REP(i, N) t += A[i] * (A[i] + 1) / 2;
    t -= r * (r + 1) / 2;

    return t;
}

signed main(){

    int N, M, K; cin >> N >> M >> K;
    vec A(N); cin >> A;
    Sort(A);

    int s = 0; REP(i, N) s += A[i];
    if(s - K <= M){
        Out(0);
        return 0;
    }

    int n = 0, r = M;
    while(A[N - 1 - n] <= r){
        r -= A[N - 1 - n];
        n++;
    }

    int ans = INF;
    Min(ans, solve(A, N - n, M, K, r));

    if(A[N - 1 - n] - r <= K){
        Min(ans, solve(A, N - n - 1, M, K - (A[N - 1 - n] - r), 0));
    }
    Out(ans);

    return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 4572
final_rank: 4

code_snippet: #include <string>
#include <vector>
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<stack>
#include<queue>
#include<cmath>
#include<algorithm>
#include<functional>
#include<list>
#include<deque>
#include<bitset>
#include<set>
#include<map>
#include<unordered_map>
#include<unordered_set>
#include<cstring>
#include<sstream>
#include<complex>
#include<iomanip>
#include<numeric>
#include<cassert>
#define X first
#define Y second
#define pb push_back
#define rep(X,Y) for (int (X) = 0;(X) < (Y);++(X))
#define reps(X,S,Y) for (int (X) = S;(X) < (Y);++(X))
#define rrep(X,Y) for (int (X) = (Y)-1;(X) >=0;--(X))
#define rreps(X,S,Y) for (int (X) = (Y)-1;(X) >= (S);--(X))
#define repe(X,Y) for ((X) = 0;(X) < (Y);++(X))
#define peat(X,Y) for (;(X) < (Y);++(X))
#define all(X) (X).begin(),(X).end()
#define rall(X) (X).rbegin(),(X).rend()
#define eb emplace_back
#define UNIQUE(X) (X).erase(unique(all(X)),(X).end())
#define Endl endl
#define NL <<"\n"

using namespace std;
using ll=long long;
using pii=pair<int,int>;
using pll=pair<ll,ll>;
template<class T> using vv=vector<vector<T>>;
template<class T> inline bool MX(T &l,const T &r){return l<r?l=r,1:0;}
template<class T> inline bool MN(T &l,const T &r){return l>r?l=r,1:0;}
//#undef NUIP
#ifdef NUIP
#include "benri.h"
#else
#define out(args...)
#endif
#ifdef __cpp_init_captures
template<typename T>vector<T> table(int n, T v){ return vector<T>(n, v);}
template <class... Args> auto table(int n, Args... args){auto val = table(args...); return vector<decltype(val)>(n, move(val));}
#endif
const ll MOD=1e9+7; //998244353

ll sumf(const vector<ll> &a,ll lb){
	ll re=0;
	for(auto x:a) re+=max(0ll,x-lb);
	return re;
}

int main(){
  ios_base::sync_with_stdio(false); cin.tie(0);
  cout<<fixed<<setprecision(0);
	int n,m;
	ll t;
	cin>>n>>m>>t;
	vector<ll> a(n);
	for(auto &x:a) cin>>x;
	sort(all(a));
	int rem=m;
	while(a.size() && rem>=a.back()){
		rem-=a.back();
		a.pop_back();
	}
	if(a.empty()){
		cout<<0 NL;
		return 0;
	}
	out(a,1);
	//keep x==rem if pos
	if(t>sumf(a,rem+1)){
		assert(a.back()>=rem);
		t-=a.back()-rem;
		rem=0;
		a.pop_back();
	}
	if(a.empty()){
		cout<<0 NL;
		return 0;
	}
	out(a,1);

	if(t>=sumf(a,0)){
		cout<<0 NL;
		return 0;
	}
	int l=0,r=MOD;
	while(r-l>1){
		int m=(l+r)/2;
		(sumf(a,m)<=t?r:l)=m;
	}
	out(a,r,1);
	t-=sumf(a,r);
	for(auto &x:a) MN<ll>(x,r);
	rep(i,t) --a[a.size()-1-i];
	sort(rall(a));
	ll re=0;
	for(ll x:a){
		ll t=min<ll>(x,rem);
		rem-=t;
		re+=x*(x+1)/2-t*(t+1)/2;
	}
	cout<<re NL;
  return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 3628
final_rank: 1

code_snippet: //#define NDEBUG
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <iostream>
#include <utility>
#include <vector>

namespace n91 {

  using i8 = std::int_fast8_t;
  using i32 = std::int_fast32_t;
  using i64 = std::int_fast64_t;
  using u8 = std::uint_fast8_t;
  using u32 = std::uint_fast32_t;
  using u64 = std::uint_fast64_t;
  using isize = std::ptrdiff_t;
  using usize = std::size_t;

  struct rep {
    struct itr {
      usize i;
      constexpr itr(const usize i) noexcept : i(i) {}
      void operator++() noexcept { ++i; }
      constexpr usize operator*() const noexcept { return i; }
      constexpr bool operator!=(const itr x) const noexcept { return i != x.i; }
    };
    const itr f, l;
    constexpr rep(const usize f, const usize l) noexcept
      : f(std::min(f, l)), l(l) {}
    constexpr auto begin() const noexcept { return f; }
    constexpr auto end() const noexcept { return l; }
  };
  struct revrep {
    struct itr {
      usize i;
      constexpr itr(const usize i) noexcept : i(i) {}
      void operator++() noexcept { --i; }
      constexpr usize operator*() const noexcept { return i; }
      constexpr bool operator!=(const itr x) const noexcept { return i != x.i; }
    };
    const itr f, l;
    constexpr revrep(const usize f, const usize l) noexcept
      : f(l - 1), l(std::min(f, l) - 1) {}
    constexpr auto begin() const noexcept { return f; }
    constexpr auto end() const noexcept { return l; }
  };
  template <class T> auto md_vec(const usize n, const T& value) {
    return std::vector<T>(n, value);
  }
  template <class... Args> auto md_vec(const usize n, Args... args) {
    return std::vector<decltype(md_vec(args...))>(n, md_vec(args...));
  }
  template <class T> constexpr T difference(const T& a, const T& b) noexcept {
    return a < b ? b - a : a - b;
  }
  template <class T> void chmin(T& a, const T& b) noexcept {
    if (b < a)
      a = b;
  }
  template <class T> void chmax(T& a, const T& b) noexcept {
    if (a < b)
      a = b;
  }
  template <class F> class rec_lambda {
    F f;

  public:
    rec_lambda(F&& f) : f(std::move(f)) {}
    template <class... Args> auto operator()(Args&&... args) const {
      return f(*this, std::forward<Args>(args)...);
    }
  };
  template <class F> auto make_rec(F&& f) { return rec_lambda<F>(std::move(f)); }
  template <class T> T scan() {
    T ret;
    std::cin >> ret;
    return ret;
  }

} // namespace n91
#include <numeric>
namespace n91 {

  void main_() {
    /*
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    //*/
    const usize n = scan<usize>();
    const u64 m = scan<u64>();
    u64 k = scan<u64>();
    std::vector<u64> a(n);
    for (auto& e : a) {
      std::cin >> e;
    }
    if (std::accumulate(a.begin(), a.end(), static_cast<u64>(0)) <= m+k) {
      std::cout << "0\n";
      return;
    }
    std::sort(a.begin(), a.end());
    usize s = n - 1;
    u64 rem = m;
    while (true) {
      if (a[s] <= rem) {
        rem -= a[s];
        s -= 1;
      }
      else {
        break;
      }
    }
    const auto get = [](const u64 a, const u64 b) {
      return (b * (b + 1) - a * (a + 1)) / 2;
    };
    u64 ups = 0;
    for (const usize i : rep(0, s + 1)) {
      if (a[i] >= rem) {
        ups += a[i] - rem;
      }
    }
    if (ups < k) {
      k -= a[s] - rem;
      rem = 0;
      s -= 1;
    }
    u64 gt = rem, le = a[s] + 1;
    while (le - gt != 1) {
      const u64 mid = (le + gt) / 2;
      u64 sum = 0;
      for (const usize i : rep(0, s + 1)) {
        if (a[i] >= mid) {
          sum += a[i] - mid;
        }
      }
      if (sum <= k) {
        le = mid;
      }
      else {
        gt = mid;
      }
    }
    u64 ans = 0;
    for (const usize i : rep(0, s)) {
      ans += get(0, std::min(a[i], le));
    }
    ans += get(rem, le);
    u64 sum = 0;
    for (const usize i : rep(0, s + 1)) {
      if (a[i] >= le) {
        sum += a[i] - le;
      }
    }
    ans -= le * (k - sum);
    std::cout << ans << std::endl;
  }

} // namespace n91

int main() {
  n91::main_();
  return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 3628
final_rank: 8

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

int main(){
    int N;
    int64_t M, K;
    cin >> N >> M >> K;
    vector<int> A(N);
    for(int i=0; i<N; i++) cin >> A[i];
    sort(A.begin(), A.end());
    int64_t S = accumulate(A.begin(), A.end(), 0LL);
    int64_t need = S-M;
    if(need <= 0){
        cout << 0 << endl;
        return 0;
    }

    vector<int64_t> num(M+1);
    for(int a : A){
        if(need > a){
            need -= a;
            num[a]++;
        }else{
            num[a]++;
            num[a-need]--;
            break;
        }
    }
    for(int i=M; i>0; i--) num[i-1] += num[i];
    int64_t ans = 0;
    for(int i=M; i>0; i--){
        int64_t dec = min(num[i], K);
        K -= dec;
        num[i] -= dec;
        ans += num[i]*i;
    }
    cout << ans << endl;
    return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 10900
final_rank: 15

code_snippet: #include<iostream>
#include<cstdio>
#include<algorithm>
#include<cassert>
#include<cmath>
#include<vector>
#include<map>
#include<set>
#include<string>
#include<queue>
#include<stack>
using namespace std;
#define MOD 1000000007
#define MOD2 998244353
#define INF ((1<<30)-1)
#define LINF (1LL<<60)
#define EPS (1e-10)
typedef long long Int;
typedef pair<Int, Int> P;
Int rest;

Int cnt(vector<Int> &a, Int m){
    Int ans = 0;
    for(int i = 0;i < a.size() - 1;i++){
        ans += max(0ll, a[i] - m + 1);
    }
    ans += a.back() - max(rest, m-1);
    return ans;
}

int main(){
    Int n, m, k;
    cin >> n >> m >> k;
    vector<Int> a(n);
    for(int i = 0;i < n;i++){
        cin >> a[i];
    }
    sort(a.begin(), a.end());

    rest = m;
    while(!a.empty() && a.back() <=rest){
        rest -= a.back();
        a.pop_back();
    }
   
    Int sum = 0;
    for(auto x:a)sum += x;
    if(sum - k - rest <= 0){
        cout << 0 << endl;
        return 0;             
    }
    
    Int bottom = 0, top = a.back() + 1;
    while(top - bottom > 1){
        Int mid = (top + bottom) / 2;
        if(cnt(a, mid) <= k)top = mid;
        else bottom = mid;
    }
    for(int i = 0;i < a.size();i++){
        Int goal = top-1;
        if(i+1 == a.size())goal = max(goal, rest);
        if(a[i] >= goal){
            k -= a[i] - goal;
            a[i] = goal;
        }
    }
    if(a.back() == rest){
        rest = 0;
        a.pop_back();
    }
    for(int i = (int)a.size()-1;i >= 0 && k > 0;i--){
        a[i]--;
        k--;
    }
    Int ans = 0;
    for(auto x:a)ans += (x+1) * x / 2;
    ans -= (rest + 1) * rest / 2;
    cout << ans << endl;
    return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 3640
final_rank: 9

code_snippet: #include <bits/stdc++.h>
#define FOR(i,k,n)  for(int i = (k);i < (n);++i)
#define REP(i,n)    FOR(i,0,n)
#define ALL(x) begin(x),end(x)

using namespace std;
using namespace std::string_literals;
using ll = int64_t;
using vecint = vector<int>;
using vecll = vector<ll>;

int main() {
  ll n,m,k;
  cin>>n>>m>>k;
  vecll a(n);
  for(auto&& e:a) cin>>e;
  sort(ALL(a));
  ll sum = 0;
  ll i;
  for(i = n-1; i >= 0; --i) {
    if (sum + a[i] > m) break;
    sum += a[i];
  }
  if (i < 0) {
    cout<<0<<endl;
    return 0;
  }
  ll rem = m - sum;
  ll lo = -1;
  ll hi = m;
  while (hi-lo > 1) {
    ll mid = (hi + lo) / 2;
    ll cnt_punch = 0;
    ll num = 0;
    REP(j,i) {
      if (a[j] > mid) ++num;
      cnt_punch += max(a[j] - mid, 0l);
    }
    ll fin = max(mid, rem);
    if (a[i] > fin && fin == mid) ++num;
    cnt_punch += max(a[i] - fin, 0l);
    if (cnt_punch - k > num) {
      lo = mid;
    } else {
      hi = mid;
    }
  }
  ll cost = 0;
  //ll num = 0;
  ll cnt_punch = 0;
  REP(j,i) {
    ll mx = min(a[j], hi); 
    cost += mx * (mx+1) / 2;
    //if (a[j] > hi) ++num;
    cnt_punch += max(a[j] - hi, 0l);
  }
  ll fin = max(hi, rem);
  ll mx = min(a[i], fin);
  cost += mx * (mx+1) / 2;
  cost -= rem * (rem+1) / 2;
  //if (a[i] > fin) ++num;
  cnt_punch += max(a[i] - fin, 0l);
  if (cnt_punch > k) {
    cost += (hi+1) * (cnt_punch - k);
  }
  cout<<cost<<endl;
  return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 3640
final_rank: 9

code_snippet: #include <bits/stdc++.h>
#include <iomanip>
using namespace std;
#define reps(i,s,n) for(int i = s; i < n; i++)
#define rep(i,n) reps(i,0,n)
#define Rreps(i,n,e) for(int i = n - 1; i >= e; --i)
#define Rrep(i,n) Rreps(i,n,0)
#define ALL(a) a.begin(), a.end()
#define fi first
#define se second
typedef long long ll;
typedef vector<ll> vec;
typedef vector<vec> mat;

ll N,M,H,W,K,Q,A,B;
string S;
const ll MOD = 998244353;
//const ll MOD = (1e+9) + 7;
const ll INF = 1LL<<60;
typedef pair<ll, ll> P;

int main() {
    cin>>N>>M>>K;
    vec a(N);
    rep(i,N) cin>>a[i];
    ll SUM = 0;
    rep(i,N) SUM += a[i];
    if(SUM - K <= M){
        cout<<0<<endl;
        return 0;
    }
    sort(ALL(a));
    reverse(ALL(a));
    ll ans = 0;
    rep(i,N) ans += a[i] * (a[i] + 1) / 2;
    int id = 0, last_sum = 0; //最後に回すやつ（これ含む）
    while(a[id] + last_sum <= M){
        last_sum += a[id];
        ans -= a[id] * (a[id] + 1)/2;
        ++id;
    }
    ll border = M - last_sum;
    ll judge = 0;
    Rreps(i, N, id) if(a[i] > border) judge += a[i] - border;
    if(judge <= K){
        K -= a[id] - border;
        ans -= a[id] * (a[id] + 1) / 2;
        ++id;
    }else{
        ans -= border * (border + 1) / 2;
    }
    a.push_back(-1);
    ll num = 1;
    ll now = a[id];
    //cout<<border<<endl;
    //cout<<ans<<endl;
    Rrep(i, now){
        while(a[id + 1] > i) {
            ++id;
            ++num;
        }
        ans -= min(num, K) * (i + 1);
        K -= num;
        if(K <= 0) break;
    }
    cout<<ans<<endl;
}
accuracy: 1
time_ms: 20
memory_kb: 4468
final_rank: 12

code_snippet: #include <iostream>
#include <cstdio>
#include <cmath>
#include <ctime>
#include <cstdlib>
#include <cassert>
#include <vector>
#include <list>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <bitset>
#include <string>
#include <algorithm>
#define llint long long
#define inf 1e18
#define mod 998244353
#define rep(x, s, t) for(llint (x) = (s); (x) < (t); (x)++)
#define Rep(x, s, t) for(llint (x) = (s); (x) <= (t); (x)++)

using namespace std;
typedef pair<llint, llint> P;

llint n, m, k;
llint a[100005];
vector<P> vec;

llint get(llint l, llint r)
{
	return r*(r+1)/2 - l*(l+1)/2;
}

int main(void)
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	
	cin >> n >> m >> k;
	for(int i = 1; i <= n; i++) cin >> a[i];
	
	llint rem = 0;
	for(int i = 1; i <= n; i++) rem += a[i];
	rem -= m;
	
	if(rem <= 0){
		cout << 0 << endl;
		return 0;
	}
	
	sort(a+1, a+n+1);
	llint ans = 0;
	for(int i = 1; i <= n; i++){
		if(rem <= 0) break;
		llint x = a[i]*(a[i]+1)/2;
		if(a[i] <= rem){
			vec.push_back(P(0, 0));
			vec.push_back(P(a[i], 1));
			rem -= a[i];
			ans += x;
		}
		else{
			llint lb = a[i]-rem+1;
			vec.push_back(P(lb-1, 0));
			vec.push_back(P(a[i], 1));
			rem = 0;
			ans += x-lb*(lb-1)/2;
		}
	}
	sort(vec.rbegin(), vec.rend());
	
	rem = k;
	llint sum = 0;
	for(int i = 0; i < vec.size(); i++){
		if(rem <= 0) break;
		
		if(vec[i].second == 1) sum++;
		else sum--;
		
		if(i < (int)vec.size()-1){
			llint dist = vec[i].first - vec[i+1].first;
			if(sum * dist <= rem){
				rem -= sum * dist;
				ans -= sum * get(vec[i+1].first, vec[i].first);
			}
			else{
				llint pos = vec[i].first - rem/sum;
				rem %= sum;
				ans -= sum * get(pos, vec[i].first);
				ans -= pos * rem;
				rem = 0;
			}
		}
	}
	cout << ans << endl;
	
	return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 7860
final_rank: 11

code_snippet: #include <bits/stdc++.h>
using namespace std;
using lint = long long int;
using pint = pair<int, int>;
using plint = pair<lint, lint>;
struct fast_ios { fast_ios(){ cin.tie(0); ios::sync_with_stdio(false); cout << fixed << setprecision(20); }; } fast_ios_;
#define ALL(x) (x).begin(), (x).end()
#define FOR(i, begin, end) for(int i=(begin),i##_end_=(end);i<i##_end_;i++)
#define IFOR(i, begin, end) for(int i=(end)-1,i##_begin_=(begin);i>=i##_begin_;i--)
#define REP(i, n) FOR(i,0,n)
#define IREP(i, n) IFOR(i,0,n)
template<typename T> void ndarray(vector<T> &vec, int len) { vec.resize(len); }
template<typename T, typename... Args> void ndarray(vector<T> &vec, int len, Args... args) { vec.resize(len); for (auto &v : vec) ndarray(v, args...); }
template<typename T> bool chmax(T &m, const T q) { if (m < q) {m = q; return true;} else return false; }
template<typename T> bool chmin(T &m, const T q) { if (m > q) {m = q; return true;} else return false; }
template<typename T1, typename T2> pair<T1, T2> operator+(const pair<T1, T2> &l, const pair<T1, T2> &r) { return make_pair(l.first + r.first, l.second + r.second); }
template<typename T1, typename T2> pair<T1, T2> operator-(const pair<T1, T2> &l, const pair<T1, T2> &r) { return make_pair(l.first - r.first, l.second - r.second); }
template<typename T> istream &operator>>(istream &is, vector<T> &vec){ for (auto &v : vec) is >> v; return is; }
template<typename T> ostream &operator<<(ostream &os, const vector<T> &vec){ os << "["; for (auto v : vec) os << v << ","; os << "]"; return os; }
template<typename T> ostream &operator<<(ostream &os, const deque<T> &vec){ os << "deq["; for (auto v : vec) os << v << ","; os << "]"; return os; }
template<typename T> ostream &operator<<(ostream &os, const set<T> &vec){ os << "{"; for (auto v : vec) os << v << ","; os << "}"; return os; }
template<typename T> ostream &operator<<(ostream &os, const unordered_set<T> &vec){ os << "{"; for (auto v : vec) os << v << ","; os << "}"; return os; }
template<typename T> ostream &operator<<(ostream &os, const multiset<T> &vec){ os << "{"; for (auto v : vec) os << v << ","; os << "}"; return os; }
template<typename T> ostream &operator<<(ostream &os, const unordered_multiset<T> &vec){ os << "{"; for (auto v : vec) os << v << ","; os << "}"; return os; }
template<typename T1, typename T2> ostream &operator<<(ostream &os, const pair<T1, T2> &pa){ os << "(" << pa.first << "," << pa.second << ")"; return os; }
template<typename TK, typename TV> ostream &operator<<(ostream &os, const map<TK, TV> &mp){ os << "{"; for (auto v : mp) os << v.first << "=>" << v.second << ","; os << "}"; return os; }
template<typename TK, typename TV> ostream &operator<<(ostream &os, const unordered_map<TK, TV> &mp){ os << "{"; for (auto v : mp) os << v.first << "=>" << v.second << ","; os << "}"; return os; }
#define dbg(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ") " << __FILE__ << endl;


lint calccost(lint x) {
    return x * (x + 1) / 2;
}

int main()
{
    lint N, M, K;
    cin >> N >> M >> K;
    vector<lint> A(N);
    cin >> A;
    sort(ALL(A));

    vector<plint> ranges;
    IREP(i, N) {
        lint pre = min(A[i], M);
        M -= pre;
        if (pre < A[i]) ranges.emplace_back(pre, A[i]);
    }
    lint no = -10, ok = 1e12;
    while (abs(ok - no) > 1) {
        lint c = (ok + no) / 2;
        lint cnt = 0;
        for (auto p : ranges) {
            if (p.second < c) continue;
            if (p.first < c) cnt += p.second - c + 1;
            else cnt += p.second - p.first;
        }
        if (cnt > K) no = c;
        else ok = c;
    }
    for (auto &p : ranges) if (p.second >= ok) {
        if (ok > p.first) {
            lint dec = p.second - ok + 1;
            K -= dec;
            p.second -= dec;
        }
        else {
            K -= p.second - p.first;
            p.second = p.first;
        }
    }
    lint ret = 0;
    for (auto p : ranges)
    {
        if (p.second == ok - 1 and p.first < p.second and K) p.second--, K--;
        if (p.first < p.second) ret = ret + calccost(p.second) - calccost(p.first);
    }
    cout << ret << endl;
}
accuracy: 1
time_ms: 10
memory_kb: 5780
final_rank: 6

code_snippet: #include <bits/stdc++.h>  // clang-format off
#define pb push_back
#define eb emplace_back
#define fi first
#define se second
#define each(x,v) for(auto& x : v)
#define all(v) (v).begin(),(v).end()
#define sz(v) ((int)(v).size())
#define ini(...) int __VA_ARGS__; in(__VA_ARGS__)
#define inl(...) long long __VA_ARGS__; in(__VA_ARGS__)
#define ins(...) string __VA_ARGS__; in(__VA_ARGS__)
#define inc(...) char __VA_ARGS__; in(__VA_ARGS__)
#define in2(s,t)     rep(i,sz(s)){in(s[i] , t[i]);}
#define in3(s,t,u)   rep(i,sz(s)){in(s[i] , t[i] , u[i]);}
#define in4(s,t,u,v) rep(i,sz(s)){in(s[i] , t[i] , u[i] , v[i]);}
#ifdef ONLINE_JUDGE
  #define rep(i,N) for(int i = 0; i < (int)(N); i++)
  #define repr(i,N) for(int i = (int)(N) - 1; i >= 0; i--)
  #define rep1(i,N) for(int i = 1; i <= (int)(N) ; i++)
  #define repr1(i,N) for(int i = (N) ; (int)(i) > 0 ; i--)
#else
  #define rep(i,N) for(long long i = 0; i < (long long)(N); i++)
  #define repr(i,N) for(long long i = (long long)(N) - 1; i >= 0; i--)
  #define rep1(i,N) for(long long i = 1; i <= (long long)(N) ; i++)
  #define repr1(i,N) for(long long i = (N) ; (long long)(i) > 0 ; i--)
#endif
using namespace std; void solve();
using ll = long long; template<class T = ll> using V = vector<T>;
using vi = V<int>; using vl = V<>; using vvi = V< V<int> >;
using vd = V<double>; using vs = V<string>; using vvl = V< V<> >;
constexpr int inf = 1001001001; constexpr ll infLL = (1LL << 61) - 1;
template<typename T, typename U> inline bool amin(T &x, U y) { return (y < x) ? (x = y, true) : false; }
template<typename T, typename U> inline bool amax(T &x, U y) { return (x < y) ? (x = y, true) : false; }
template<typename T,typename U>ll ceil(T a,U b){return (a + b - 1) / b;}
template<typename T, typename U> ostream& operator <<(ostream& os, const pair<T, U> &p) { os << p.first << " " << p.second; return os; }
template<typename T, typename U> istream& operator >>(istream& is, pair<T, U> &p) { is >> p.first >> p.second; return is; }
template<typename T> ostream& operator <<(ostream& os, const vector<T> &v) { int s = (int)v.size(); for(int i=0;i<s;i++) os << (i ? " " : "") << v[i]; return os; }
template<typename T> istream& operator >>(istream& is, vector<T> &v) { for(auto &x : v) is >> x; return is; }
void in(){} template <typename T,class... U> void in(T &t,U &...u){ cin >> t; in(u...);}
void out(){cout << "\n";} template <typename T,class... U> void out(const T &t,const U &...u){ cout << t; if(sizeof...(u)) cout << " "; out(u...);}
template<typename T>void die(T x){out(x); exit(0);}

#ifdef NyaanDebug
  #include "NyaanDebug.h"
  #define trc(...) do { cerr << #__VA_ARGS__ << " = "; dbg_out(__VA_ARGS__);} while(0)
  #define trca(v,N) do { cerr << #v << " = "; array_out(v , N);} while(0)
  #define trcc(v) do { cerr << "name : " << #v << "\n"; int cnt = 0; each(x , v){cerr << (cnt++) << " : "; trc(x); } } while(0)
#else
  #define trc(...)
  #define trca(...)
  #define trcc(...)
  int main(){solve();}
#endif

constexpr ll TEN(int n){ll ret=1,x=10;while(n){if(n&1)ret*=x;x*=x;n>>=1;}return ret;}
#define mem(a, val) memset(a, val, sizeof(a))

struct IoSetupNya {IoSetupNya() { cin.tie(nullptr); ios::sync_with_stdio(false); cout << fixed << setprecision(15); cerr << fixed << setprecision(7);} } iosetupnya;
using P = pair<ll,ll>; using vp = V<P>;
constexpr int MOD = /** 1000000007; //*/ 998244353;
// clang-format on
////////////////////////////////////////////////////

void solve(){
  inl(N , M , K);
  vl a(N); in(a);
  sort(all(a));
  ll ss = accumulate(all(a),0LL);
  if(ss <= M + K) die(0);

  int r = N;
  ll s = 0;
  while(r != 0 && s + a[r - 1] <= M){
    s += a[r - 1];
    r--;
  }
  // 
  // r - 1番目の特殊条件
  ll rmin = M - s;

  // [ 0 , r )
  trc(s , r , rmin);
  // 実装が難しい
  
  // maxをxに出来ますか？
  ll ng = -1 , ok = M;
  while(ng + 1 < ok){
    ll med = (ng + ok) / 2;
    ll cur = 0;
    rep(i , r){
      if(i != r - 1) cur += max(0LL , a[i] - med);
      else cur += max(0LL , a[i] - max(med,rmin) );
    }
    (cur <= K ? ok : ng) = med;
  }

  trc(ok);
  
  rep(i , r){
    if(i != r - 1){
      if(a[i] > ok){
        K -= a[i] - ok;
        a[i] = ok;
      }
    }
    else{
      if(a[i] > max(rmin,ok) ){
        K -= a[i] - max(rmin,ok);
        a[i] = max(rmin,ok);
      }
    }
  }

  repr(i , r){
    if(i == r - 1 && a[i] == rmin) continue;
    if(K == 0) break;
    a[i]--; K--;
  }

  ll ans = -(rmin) * (rmin + 1) / 2;

  rep(i , r){
    ans += a[i] * (a[i] + 1) / 2;
  }
  out(ans);



  
  



}
accuracy: 1
time_ms: 10
memory_kb: 3640
final_rank: 2

code_snippet: #include <algorithm>
#include <bitset>
#include <cassert>
#include <chrono>
#include <climits>
#include <cmath>
#include <complex>
#include <cstring>
#include <deque>
#include <functional>
#include <iostream>
#include <iomanip>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <cstdint>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> pii;
#define MP make_pair
#define PB push_back
#define inf 1000000007
#define rep(i,n) for(int i = 0; i < (int)(n); ++i)
#define all(x) (x).begin(),(x).end()

template<typename A, size_t N, typename T>
void Fill(A (&array)[N], const T &val){
    std::fill( (T*)array, (T*)(array+N), val );
}
 
template<class T> inline bool chmax(T &a, T b){
    if(a<b){
        a = b;
        return true;
    }
    return false;
}

template<class T> inline bool chmin(T &a, T b){
    if(a>b){
        a = b;
        return true;
    }
    return false;
}

ll dp[1000010];
int main(){
    int n;
    cin >> n;
    ll m,k;
    cin >> m >> k;
    vector<ll>a(n);
    rep(i,n)cin >> a[i];
    sort(a.rbegin(),a.rend());
    bool flag = 1;
    ll sm = 0;
    
    for(int i=0;i<n;i++){
        if(flag){
            if(sm + a[i]<=m){
                sm += a[i];
            }else{
                flag = 0;
                dp[a[i]]++;
                dp[m-sm]--;
            }
        }else{
            dp[a[i]]++;
            dp[0]--;
        }
    }
    ll cnt = 0;
    ll res = 0;
    for(ll i=1000001;i>=0;i--){
        cnt += dp[i];
        if(cnt==0)continue;
        if(k>0){
            if(k>cnt){
                k-=cnt;
            }else{
                res += (cnt-k)*i;
                k = 0;
            }
        }else{
            res += cnt*i;
        }
    }
    cout << res << endl;
    return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 11468
final_rank: 16

code_snippet: #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> l_l;
typedef pair<int, int> i_i;
template<class T>
inline bool chmax(T &a, T b) {
    if(a < b) {
        a = b;
        return true;
    }
    return false;
}

template<class T>
inline bool chmin(T &a, T b) {
    if(a > b) {
        a = b;
        return true;
    }
    return false;
}

const long double EPS = 1e-10;
const long long INF = 1e18;
const long double PI = acos(-1.0L);
//const ll mod = 1000000007;
ll N, M, K;

ll imos[1005000];

int main() {
    cin >> N >> M >> K;
    vector<ll> A(N);
    for(int i = 0; i < N; i++) cin >> A[i];
    sort(A.begin(), A.end());
    ll sum = 0;
    for(int i = N - 1; i >= 0; i--) {
        ll rest = M - sum;
        if(rest < A[i]) {
            imos[A[i]]++;
            ll tmp = A[i] - rest;
            imos[A[i]-tmp]--;
            //cerr << i << " " << A[i] << " " << A[i]- tmp - 1 << endl;
        }
        sum += A[i];
        chmin(sum, M);
    }
    for(int i = 1e6; i >= 0; i--) {
        imos[i] += imos[i+1];
    }
    /*
    for(int i = 0; i <= 10; i++) {
        cerr << i << " "<< imos[i] << endl;
    }
    */
    ll ans = 0;
    for(int i = 1e6; i >= 1; i--) {
        ll tmp = min(imos[i], K);
        imos[i] -= tmp;
        K -= tmp;
        //if(i <= 10) cerr << i << " " << imos[i] << endl;
        ans += i * imos[i];
    }
    cout << ans << endl;
    return 0;
}
accuracy: 1
time_ms: 30
memory_kb: 11596
final_rank: 17