提交时间:2022-07-20 11:53:43
运行 ID: 52779
#include <bits/stdc++.h> #define ll long long using namespace std; const int maxn=1e6+5; multiset<int> bst; int a[maxn],ans[maxn],n; int id[maxn]; bool cmp(int i,int j){ return a[i]>a[j]; } int main(){ scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%d",&a[i]),id[i]=i; sort(id+1,id+n+1,cmp); for(int j=1;j<=n;j++){ int i=id[j]; int s=j;while(a[id[j+1]]==a[i]&&j+1<=n) j++; //cout<<s<<" "<<j<<endl; for(int x=s;x<=j;x++){ if(bst.empty()) continue; //cout<<*bst.begin()<<endl; if(*bst.begin()>id[x]) continue; ans[id[x]]=a[*bst.begin()]-a[id[x]]; } for(int x=s;x<=j;x++){ bst.insert(id[x]); } } ll sum=0; for(int i=1;i<=n;i++){ sum+=ans[i]; //cout<<ans[i]<<endl; } printf("%lld",sum); }