P6155 修改 题解
Daniel_yao · · 题解
Problem
给定一个长度为
Solve
首先,有一个很显然的结论,就是对于一个数列
按照这个去做,直觉上非常的完美,实际上会被这个样例给 hack 掉:
10
1 1 4 5 1 4 1 9 1 9
9 8 1 1 4 5 6 2 3 5
你会发现,有
可以用一个栈去实现,因为每次都要用距离空位更近的数去填补,所以每次将数压入栈内,当遇到空位是,栈顶元素,也就是最后压入的点,就是我要将其填补的数。
时间复杂度
#include <bits/stdc++.h>
#define int unsigned long long
#define H 19260817
#define rint register int
#define For(i,l,r) for(rint i=l;i<=r;++i)
#define FOR(i,r,l) for(rint i=r;i>=l;--i)
#define MOD 1000003
using namespace std;
inline int read() {
rint x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}
return x*f;
}
void print(__int128 x){
if(x<0){putchar('-');x=-x;}
if(x>9){print(x/10);putchar(x%10+'0');}
else putchar(x+'0');
return;
}
const int N = 2e6 + 10;
int n, a[N], b[N], res[N], k, tot, stk[N], top;
long long cnt = 0;
int ans;
signed main() {
n = read();
For(i,1,n) a[i] = read();
For(i,1,n) b[i] = read();
sort(b + 1, b + n + 1);
sort(a + 1, a + n + 1);
a[n+1] = 1e18;
For(i,2,n+1) {
if(a[i] == a[i-1]) stk[++top] = i;
else {
int l = a[i-1];
while(top && l < a[i] - 1) {
l++;
res[++tot] = (l - a[stk[top]]);
top--;
}
}
}
sort(res + 1, res + tot + 1, [](int a, int b){return a > b;});
For(i,1,tot) k++, ans += 1ull * res[i] * b[k];
print(ans);
puts("");
return 0;
}