AT_arc116_b [ARC116B] Products of Min-Max

思路

我们容易可以得到一个朴素的做法,首先对 aa 数组排序,然后枚举最大值和最小值 ai,aja_i,a_j,那么对于中间的元素都有选与不选两种情况,得到答案:

i=1n(ai×ai+(j=i+1nai×aj×2ji1)) \sum_{i = 1}^{n}(a_i \times a_i + (\sum_{j = i + 1}^{n}a_i \times a_j \times 2^{j - i - 1}))

然后对这个式子做一个化简:

i=1n(ai×ai+ai×(j=i+1naj×2ji1)) \sum_{i = 1}^{n}(a_i \times a_i + a_i \times (\sum_{j = i + 1}^{n}a_j \times 2^{j - i - 1}))

发现对于每一个 iiaj×2ji1a_j \times 2^{j - i - 1} 都是类似的,所以考虑预处理。

定义 mi=j=1i(aj×2j)m_i = \sum_{j = 1}^{i}(a_j \times 2^j),那么发现:

mnmi=j=i+1naj×2j m_n - m_i = \sum_{j = i + 1}^{n}{a_j}\times 2^j

然后,发现对于每一项 jj 对于原式都多乘了一个 2i+12^{i + 1},直接除掉即可。得答案为:

i=1n(ai×ai+mnmi2i+1×ai) \sum_{i = 1}^n{(a_i \times a_i + \frac{m_n - m_i}{2^{i + 1}} \times a_i)}

时间复杂度 Θ(nlogn)\Theta(n \log n)

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <bits/stdc++.h>  
#define int long long
#define re register

using namespace std;

const int N = 2e5 + 10,mod = 998244353;
int n,ans;
int arr[N],pot[N],mul[N],inv[N];

inline int read(){
int r = 0,w = 1;
char c = getchar();
while (c < '0' || c > '9'){
if (c == '-') w = -1;
c = getchar();
}
while (c >= '0' && c <= '9'){
r = (r << 3) + (r << 1) + (c ^ 48);
c = getchar();
}
return r * w;
}

inline int Add(int a,int b){
return (a + b) % mod;
}

inline int Sub(int a,int b){
return ((a - b) % mod + mod) % mod;
}

inline int Mul(int a,int b){
return a * b % mod;
}

inline void exgcd(int a,int b,int &x,int &y){
if (!b){
x = 1;
y = 0;
return;
}
exgcd(b,a % b,y,x);
y = y - a / b * x;
}

inline int get_inv(int a,int p){
int x,y;
exgcd(a,p,x,y);
return (x % mod + mod) % mod;
}

inline void init(){
pot[0] = 1;
for (re int i = 1;i <= n + 1;i++){
pot[i] = Mul(pot[i - 1],2);
mul[i] = Add(mul[i - 1],Mul(arr[i],pot[i]));
inv[i] = get_inv(pot[i],mod);
}
}

signed main(){
n = read();
for (re int i = 1;i <= n;i++) arr[i] = read();
sort(arr + 1,arr + n + 1);
init();
for (re int i = 1;i <= n;i++){
ans = Add(ans,Mul(Mul(Sub(mul[n],mul[i]),inv[i + 1]),arr[i]));
ans = Add(ans,Mul(arr[i],arr[i]));
}
printf("%lld",ans);
return 0;
}

AT_arc116_b [ARC116B] Products of Min-Max
http://watersun.top/[题解]AT_arc116_b [ARC116B] Products of Min-Max/
作者
WaterSun
发布于
2023年9月12日
许可协议