维护前缀和,排序
#include<bits/stdc++.h> using namespace std; typedef long long ll; #define maxn 100004 ll sum[maxn]; vector<ll>v; int main() { int t; int n,m; scanf("%d",&t); while(t--){ scanf("%d%d",&n,&m); ll t; v.clear(); for(int i=1;i<=n;i++){ scanf("%lld",&t); sum[i]=sum[i-1]+t; } int a,b; for(int i=1;i<=m;i++){ scanf("%d%d",&a,&b); v.push_back(sum[b]-sum[a-1]); } sort(v.begin(),v.end()); ll ans=0; for(int i=0;i<m;i++){ ans+=(i+1)*v[i]; } cout<<ans<<'\n'; } }