题解 (by;zjvarphi)
最终的序列在求出来后肯定不变,就是看新产生的值是由哪个值变化而来的。
贪心策略,当两个数所生成的值交换后,差值总和不变,应当让最小的生成最大的。
直接模拟即可。
Code
#include<bits/stdc++.h>
#define ri signed
#define pd(i) ++i
#define bq(i) --i
#define func(x) std::function<x>
namespace IO{
char buf[1<<21],*p1,*p2;
#define gc() p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?(-1):*p1++
#define dg1(x) std::cerr << #x"=" << x << ' '
#define dg2(x) std::cerr << #x"=" << x << std::endl
#define Dg(x) assert(x)
struct nanfeng_stream{
template<typename T>inline nanfeng_stream &operator>>(T &x) {
bool f=false;x=0;char ch=gc();
while(!isdigit(ch)) f|=ch=='-',ch=gc();
while(isdigit(ch)) x=(x<<1)+(x<<3)+(ch^48),ch=gc();
return x=f?-x:x,*this;
}
}cin;
}
using IO::cin;
namespace nanfeng{
#define pb push
#define mk std::make_pair
#define fi first
#define se second
#define FI FILE *IN
#define FO FILE *OUT
template<typename T>inline T cmax(T x,T y) {return x>y?x:y;}
template<typename T>inline T cmin(T x,T y) {return x>y?y:x;}
static const int N=1e6+7;
using ull=unsigned long long;
int a[N],b[N],st[N],bs[N],al,cn,cnt,nm,mn,n,ct;
// bool vis[N<<1];
// std::vector<std::pair<int,int>> vc[N];
std::stack<std::pair<int,int>> sta;
std::unordered_map<int,bool> vis;
ull ans;
inline int main() {
FI=freopen("openhook.in","r",stdin);
FO=freopen("openhook.out","w",stdout);
cin >> n;
for (ri i(1);i<=n;pd(i)) cin >> a[i];
for (ri i(1);i<=n;pd(i)) cin >> b[i];
std::sort(a+1,a+n+1);
std::sort(b+1,b+n+1);
mn=a[1];
for (ri i(1);i<=n;pd(i)) vis[a[i]]=true;
a[n+1]=N+(int)2e9;
for (ri i(1);i<=n+1;pd(i))
if (a[i]!=a[i-1]) {
const int tmp=a[i-1];
nm=cmax(nm,tmp);
if (cnt>1) {
for (ri j(i-cnt+1);j<i;pd(j)) {
while(vis.find(nm)!=vis.end()) ++nm;
vis[nm]=true;
}
cnt-=1;
int ttc=0;
for (ri j(tmp+1);j<a[i];pd(j)) {
st[++al]=j-tmp;
++ttc;
if (ttc>=cnt) break;
}
for (ri j(tmp+ttc+1);j<cmin(a[i],nm+1);pd(j)) {
st[++al]=j-sta.top().fi;
sta.top().se-=1;
if (!sta.top().se) sta.pop();
}
if (cnt-ttc) sta.pb(mk(tmp,cnt-ttc));
} else
for (ri j(tmp+1);j<cmin(a[i],nm+1);pd(j)) {
st[++al]=j-sta.top().fi;
sta.top().se-=1;
if (!sta.top().se) sta.pop();
}
if (nm<a[i]) Dg(sta.empty());
cnt=1;
} else ++cnt;
std::sort(st+1,st+al+1,[](int x,int y) {return x>y;});
for (ri i(1);i<=al;pd(i)) ans+=1ull*st[i]*b[i];
printf("%llu
",ans);
return 0;
}
}
int main() {return nanfeng::main();}