E. Two Arrays and Sum of Functions
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
You are given two arrays a
and b, both of length n
.
Let's define a function f(l,r)=∑l≤i≤rai⋅bi
.
Your task is to reorder the elements (choose an arbitrary order of elements) of the array b
to minimize the value of ∑1≤l≤r≤nf(l,r). Since the answer can be very large, you have to print it modulo 998244353
. Note that you should minimize the answer but not its remainder.
Input
The first line of the input contains one integer n
(1≤n≤2⋅105) — the number of elements in a and b
.
The second line of the input contains n
integers a1,a2,…,an (1≤ai≤106), where ai is the i-th element of a
.
The third line of the input contains n
integers b1,b2,…,bn (1≤bj≤106), where bj is the j-th element of b
.
Output
Print one integer — the minimum possible value of ∑1≤l≤r≤nf(l,r)
after rearranging elements of b, taken modulo 998244353
. Note that you should minimize the answer but not its remainder.
Examples
Input
Copy
5 1 8 7 2 4 9 7 2 9 3
Output
Copy
646
Input
Copy
1 1000000 1000000
Output
Copy
757402647
Input
Copy
2 1 3 4 2
Output
Copy
20
这个题大意是给你数组a和数组b然后可以对b进行随意的排序
如何使得题目中的表达式结果最小
我一开始想得是直接对a和b分别排序
a从小到大 b从大到小
然后a[i]*b[i]都是计算了n次直接输出结果
但是快结束的时候才发现 a[i]其实计算了i*(n-i+1)次(i从1开始)
所以这时候我们先处理一下a[i] a[i]=a[i]*i*(n-i+1) 然后把处理过的a[i]进行排序就可以了
(让b[i]最大乘以a[i]最小)
/*#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;typedef long long ll;
ll a[200000+100];
ll b[200000+100];
ll qian[200000+100];
#define mu 998244353
bool cmp(const int a,const int b){
return a>b;
}
int num[10000];
int main(){
int n;
cin>>n;
for(int i =1;i<=n;++i){
scanf("%lld",&a[i]);
}
for(int i = 1;i<=n;++i){
scanf("%lld",&b[i]);
}
sort(a+1,a+n+1);
sort(b+1,b+n+1,cmp);
for(int i =1;i<=n;++i){
cout<<a[i]<<":";
}
cout<<endl;
for(int i =1;i<=n;++i){
cout<<b[i]<<":";
}
cout<<endl;
ll sum = 0;
for(int i =1;i<=n;++i){
sum+=((((a[i]*b[i])%mu)*n)%mu)%mu;
//cout<<sum<<endl;
}
for(int i =1;i<=n;++i){
for(int j =i;j<=n;++j){
for(int k=i;k<=j;++k){
sum+=a[k]*b[k];
num[k]++;
cout<<k<<":";
}
cout<<endl;
}
}
for(int i =1;i<=n;++i){
cout<<num[i]<<endl;
}
cout<<sum<<endl;
}
*/
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
#define mu 998244353
ll a[1000000+100];
ll b[1000000+100];
bool cmp(const int a,const int b){
return a>b;
}
int main(){
int n;
cin>>n;
for(int i =1;i<=n;++i){
scanf("%lld",&a[i]);
a[i]=a[i]*(i)*(n-i+1);
}
for(int i =1;i<=n;++i){
scanf("%lld",&b[i]);
}
sort(a+1,a+1+n);
sort(b+1,b+1+n,cmp);
ll res = 0;
for(int i =1;i<=n;++i){
res=(res+(a[i]%mu)*(b[i]%mu))%mu;
}
cout<<res<<endl;
}