結果
| 問題 | No.2169 To Arithmetic |
| コンテスト | |
| ユーザー |
hotman78
|
| 提出日時 | 2022-12-24 17:18:03 |
| 言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 369 ms / 2,000 ms |
| コード長 | 2,139 bytes |
| コンパイル時間 | 2,380 ms |
| コンパイル使用メモリ | 210,100 KB |
| 最終ジャッジ日時 | 2025-02-09 20:07:40 |
|
ジャッジサーバーID (参考情報) |
judge1 / judge4 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 25 |
ソースコード
#include<bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for(int i=(a);i<(b);++i)
#define all(n) (n).begin(),(n).end()
using lint=long long;
/**
* Author: Simon Lindholm
* Date: 2017-04-20
* License: CC0
* Source: own work
* Description: Container where you can add lines of the form kx+m, and query maximum values at points x.
* Useful for dynamic programming (``convex hull trick'').
* Time: O(\log N)
* Status: stress-tested
*/
using ll=long long;
struct Line {
mutable ll k, m, p;
bool operator<(const Line& o) const { return k < o.k; }
bool operator<(ll x) const { return p < x; }
};
struct LineContainer : multiset<Line, less<>> {
// (for doubles, use inf = 1/.0, div(a,b) = a/b)
static const ll inf = LLONG_MAX;
ll div(ll a, ll b) { // floored division
return a / b - ((a ^ b) < 0 && a % b); }
bool isect(iterator x, iterator y) {
if (y == end()) return x->p = inf, 0;
if (x->k == y->k) x->p = x->m > y->m ? inf : -inf;
else x->p = div(y->m - x->m, x->k - y->k);
return x->p >= y->p;
}
void add(ll k, ll m) {
auto z = insert({k, m, 0}), y = z++, x = y;
while (isect(y, z)) z = erase(z);
if (x != begin() && isect(--x, y)) isect(x, y = erase(y));
while ((y = x) != begin() && (--x)->p >= y->p)
isect(x, erase(y));
}
ll query(ll x) {
assert(!empty());
auto l = *lower_bound(x);
return l.k * x + l.m;
}
};
int main(){
cin.tie(0)->sync_with_stdio(0);
lint n,q;
cin>>n>>q;
vector<lint>a(n);
rep(i,0,n)cin>>a[i];
map<lint,lint>memo;
LineContainer lc;
rep(i,0,n)lc.add(-i,a[i]);
lint sum=0;
rep(i,0,n)sum+=a[i];
vector<lint>dd(n-1);
rep(i,1,n)dd[i-1]+=a[i]-a[i-1];
sort(all(dd));
vector<lint>dsum(n);
rep(i,0,n-1)dsum[i+1]=dd[i]+dsum[i];
while(q--){
lint d;
cin>>d;
if(memo.count(d)){
cout<<memo[d]<<endl;
continue;
}
lint mn=1LL<<60;
lint x=lc.query(d);
auto e=lower_bound(all(dd),d)-dd.begin();
lint ans=(d*e-dsum[e])+((dsum.back()-dsum[e])-d*(n-1-e));
cout<<(ans+abs(x+(n-1)*d-a.back())+abs(a[0]-x))/2<<endl;
}
}
hotman78