AtCoder-abc255_d ±1 Operation 2
作者:互联网
±1 Operation 2
离线 + 尺取 或者 直接二分
二分更简单
二分一下当前询问的数 \(X\) 的位置 \(index\),左边(小于等于当前数)的每一个数字的贡献都为 \(X - A_i\),右边(大于当前数)的每一个数字的贡献都为 \(A_i - X\),因此考虑求和的时候用前缀和优化一下就好
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 2e5 + 10;
#define endl '\n'
ll num[maxn], sum[maxn];
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n, q;
cin >> n >> q;
for(int i=1; i<=n; i++)
cin >> num[i];
sort(num + 1, num + n + 1);
for(int i=1; i<=n; i++) sum[i] = sum[i-1] + num[i];
while(q--)
{
ll x;
cin >> x;
ll way = lower_bound(num + 1, num + n + 1, x) - num;
ll ans = 0;
ll l = way - 1;
ans += l * x - sum[l];
ll r = n - l;
ans += sum[n] - r * x - sum[l];
cout << ans << endl;
}
return 0;
}
离线 + 尺取
考虑到对 \(A\) 和 \(X\) 进行离线排序,然后双指针找前一个询问和当前询问之间,使得数字的差“变向”的地方,即 \(A_{i-1} < x_j \leq A_{i}\),然后补齐这个差值,然后对于左端无变向的就是一直增大,右端就是减小,整个过程就是递推答案
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <string>
#include <queue>
#include <functional>
#include <map>
#include <set>
#include <cmath>
#include <cstring>
#include <deque>
#include <stack>
using namespace std;
typedef long long ll;
#define pii pair<ll, ll>
const ll maxn = 2e5 + 10;
const ll inf = 1e17 + 10;
ll a[maxn], ans[maxn];
pii q[maxn];
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n, m;
cin >> n >> m;
ll sum = 0;
for(int i=0; i<n; i++)
{
cin >> a[i];
sum += a[i];
}
sum += n;
for(int i=0; i<m; i++)
{
ll x;
cin >> x;
q[i] = {x, i};
}
sort(a, a + n);
sort(q, q + m);
ll l = 0, r = 0, pre = -1;
for(int i=0; i<m; i++)
{
while(r < n && a[r] <= q[i].first)
r++;
for(int j=l; j<r; j++)
{
sum -= a[j] - pre;
sum += q[i].first - a[j];
}
sum += (q[i].first - pre) * l;
sum -= (q[i].first - pre) * (n - r);
l = r;
pre = q[i].first;
ans[q[i].second] = sum;
}
for(int i=0; i<m; i++)
cout << ans[i] << endl;
return 0;
}
标签:AtCoder,int,ll,num,maxn,sum,abc255,include,Operation 来源: https://www.cnblogs.com/dgsvygd/p/16369622.html