题目:
Description:
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 aiai is 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 bjbj is 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.
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
题意:
两段序列,a和b,通过改变序列b来让 f(l,r) 最小,这里的l-r就是区间长度,f的值是需要把所有区间长度都算一下的,从长度为1到长度为n的所有可能都需要算一下,通过找规律,我们得到对应关系:
a[1] a[2] a[3] a[4] a[5]
b[1] b[2] b[3] b[4] b[5]
1*n 2*(n-1) 3*(n-2) 4*(n-3) 5*(n-4)
从a[i]*b[i]出现的次数为i*(n-i+1)
大部分人会想把a与b从小到大进行配对,即a的小对应b的大,这里有一个问题是,a的小对应b的大不是全局最优解,只能算是局部最优解,因为答案是 ans+=(a[i]*b[i]*i*(n-i+1)),所以我们先把a预处理一下,即a[i]=a[i]*i*(n-i+1),然后这样对a,b进行匹配,但是这个题目当算最终的a[i]*b[i]的时候会爆long long,所以我们应该加上一个快速乘来得到最终答案,注意一点,输出最终答案还要去模!!!!我忽略了这一点,卡了好久第四个点
代码:
#include<bits/stdc++.h>
#define N 200005
#define LL long long
#define MOD 998244353
using namespace std;
struct ljh
{
LL u,num;
}e[N];
LL n;
LL b[N],a[N],c[N],d[N],ans=0;
bool cmp(ljh x,ljh y)
{
return x.u>y.u;
}
LL makefast(LL a,LL b)//快速乘
{
LL ans=0;
while(b)
{
if(b&1)ans=(ans+a)%MOD;
a=(a+a)%MOD;
b/=2;
}
return ans;
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%lld",&a[i]);
a[i]=a[i]*i*(n-i+1);
e[i].u=a[i];
e[i].num=i;
}
for(int i=1;i<=n;i++)scanf("%lld",&b[i]);
sort(e+1,e+n+1,cmp);
sort(b+1,b+n+1);
for(int i=1;i<=n;i++)
{
c[e[i].num]=b[i];//c为最终b匹配a后变成的数组,可以输出查看
}
for(int i=1;i<=n;i++)
{
ans+=makefast(a[i],c[i])%MOD;
}
printf("%lld",ans%MOD);
return 0;
}