CF--A - Two Arrays and Sum of Functions --排序不等式

You are given two arrays aa and bb, both of length nn.

Let's define a function f(l,r)=∑l≤i≤rai⋅bif(l,r)=∑l≤i≤rai⋅bi.

Your task is to reorder the elements (choose an arbitrary order of elements) of the array bb to minimize the value of ∑1≤l≤r≤nf(l,r)∑1≤l≤r≤nf(l,r). Since the answer can be very large, you have to print it modulo 998244353998244353. Note that you should minimize the answer but not its remainder.

Input

The first line of the input contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of elements in aa and bb.

The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1061≤ai≤106), where aiaiis the ii-th element of aa.

The third line of the input contains nn integers b1,b2,…,bnb1,b2,…,bn (1≤bj≤1061≤bj≤106), where bjbjis the jj-th element of bb.

Output

Print one integer — the minimum possible value of ∑1≤l≤r≤nf(l,r)∑1≤l≤r≤nf(l,r) after rearranging elements of bb, taken modulo 998244353998244353. Note that you should minimize the answer but not its remainder.

Examples

Input

5
1 8 7 2 4
9 7 2 9 3

Output

646

Input

1
1000000
1000000

Output

757402647

Input

2
1 3
4 2

Output

20

问给定两个数组,第一个不变,第二个可以重排,问重排后可以组成的函数最小值是多少。

思路:

假如N=3    a1 a2 a3  假设我们重排的b数组为c数组  c1 c2 c3

计算函数和值为 3a1b1+4a2b2+3a3b3,再写几个相似的式子,发现和值可以变化为sum(  i*(n-i+1)*ai*ci   )。

每个ai相当于要算i*(n-i+1)次,记di=i*(n-i+1)*ai。我们将d和c数组按不同的顺序排序,逆序,和为最小。

想一下,这里仍然满足a数组不改变,只是这样可以处理出对于每一个ai,它所对应的是哪个bi,本质上a数组是没有变化的。

#include
using namespace std;
#define ll long long
const int maxn=200000+66;
const int mod=998244353;
int n;
ll a[maxn];
ll b[maxn];
bool cmp(ll a,ll b)
{
    return a>b;
}
int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)scanf("%lld",&a[i]);
    for(int i=1;i<=n;i++)scanf("%lld",&b[i]);
    for(int i=1;i<=n;i++)a[i]=((a[i]*i)*(n-i+1));//这里不能模,因为还要做排序操作。
    sort(a+1,a+n+1);
    sort(b+1,b+n+1);//---
    ll s=0;
    for(int i=1;i<=n;i++)
    {
        s=(s+(a[i]%mod)*b[n-i+1]%mod)%mod;//---//
        s%=mod;
    }
    printf("%lld\n",s);
}

 

你可能感兴趣的:(模拟)