解法:

%E6%9F%A5%E8%AF%A2%E7%9A%84%E5%81%9A%E6%B3%95(%E6%B2%A1%E7%94%A8%E4%BA%8C%E5%88%86)%3A&preview=true)


%2C%E6%8E%A5%E7%9D%80%E5%BE%80%E4%B8%8B%E7%9C%8B&preview=true)









%2F2%5D%E5%8C%BA%E9%97%B4%E7%9A%84%E5%91%98%E5%B7%A5%E9%83%BD%E5%8E%BBa%2C%5Ba%2B(b-a)%2F2%20%2B%201%2Cb-1%5D%E5%8C%BA%E9%97%B4%E7%9A%84%E5%91%98%E5%B7%A5%E9%83%BD%E5%8E%BBb&preview=true)
%E5%A4%84%E7%90%86%EF%BC%8C%E4%BD%A0%E5%8F%AF%E4%BB%A5%E7%90%86%E8%A7%A3%E6%88%90%E5%9C%A8%5Ba%2Cb%5D%E4%B8%AD%E9%97%B4%E5%88%87%E4%B8%80%E5%88%80%EF%BC%8C%E5%B7%A6%E5%8D%8A%E9%83%A8%E5%88%86%E5%8E%BBa%EF%BC%8C%E5%8F%B3%E5%8D%8A%E9%83%A8%E5%88%86%E5%8E%BBb%EF%BC%8C%E7%BB%86%E8%8A%82%E5%B0%B1%E4%B8%8D%E5%86%8D%E7%AE%80%E8%BF%B0&preview=true)
时间复杂度:
&preview=true)
std:
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn = 100005;
int a[maxn] , b[maxn];
ll pre[maxn] , fpre[maxn];
ll cpre[maxn] , cfpre[maxn];
int main()
{
int n,q;
cin>>n>>q;
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
b[a[i]]++;
}
ll sum = 0,sum2 = 0;
for(int i=1;i<=100000;i++){
if(b[i]){
sum += 1ll*i*b[i];
sum2 += 1ll*b[i];
}
pre[i] = sum;
cpre[i] = sum2;
}
sum = 0,sum2 = 0;
for(int i=100000;i>=1;i--){
if(b[i]){
sum += 1ll*i*b[i];
sum2 += 1ll*b[i];
}
fpre[i] = sum;
cfpre[i] = sum2;
}
while(q--){
int l,r;
ll ans = 0;
scanf("%d %d",&l,&r);
if(l > r)
swap(l , r);
ll x = 1ll*cpre[l]*l - 1ll*pre[l];
ll y = 1ll*fpre[r] - 1ll*cfpre[r]*r;
ll z = 0 , w = 0;
if(r - l > 1){
int x = r - l;
int l2 = l + x/2;
z = pre[l2] - pre[l] - (cpre[l2] - cpre[l])*l;
int r2 = l2;
w = r*(cpre[r-1] - cpre[r2]) - (pre[r-1] - pre[r2]);
}
cout<<x + y + z + w<<endl;
}
return 0;
}