T3-修改
一道很水的贪心题,由于太水了,就直接对正解进行讲解。
首先,如果没有
举个例子。
假如有
枚举位置
枚举位置
枚举位置
枚举位置
每个点被修改的次数即为 出队时间
但有时有多种选择,比如在上述样例中,时间
所以将上述的队列改为栈。
但时间复杂度还是
但可以发现,其实很多时候栈都是空的,优化就是在栈为空的时候跳到下一个
可以证明栈有值的点至多有
总复杂度
#pragma GCC optimize(2,3,4,5)
#include<bits/stdc++.h>
#define re register
using namespace std;
struct node{
int x,id;
};
struct d{
int ans,pos;
}p[1000002];
int n,a[1000002],b[1000002],x,l;
unsigned long long ans;
inline int read(){
int t=0;
char v=getchar();
while(v<'0')v=getchar();
while(v>='0'){
t=(t<<3)+(t<<1)+v-48;
v=getchar();
}
return t;
}
inline bool cmp(re d x,re d y){
return x.ans>y.ans;
}
stack <node> q;
signed main(){
n=read();
for(re int i=1;i<=n;++i)a[i]=read();
sort(a+1,a+n+1);
for(re int i=1;i<=n;++i)b[i]=read();
sort(b+1,b+n+1);
l=1;
x=1;
while(1){
if(q.empty()){
if(l<=n)
x=a[l];
else break;
}
while(a[l]==x){
q.push(node{a[l],l});
++l;
}
node tmp=q.top();
q.pop();
p[tmp.id].ans=x-tmp.x;
++x;
}
sort(p+1,p+n+1,cmp);
for(re int i=1;i<=n;++i){ans+=1llu*p[i].ans*b[i];
}
printf("%llu",ans);
}