B. Views Matter
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
You came to the exhibition and one exhibit has drawn your attention. It consists of nn stacks of blocks, where the ii-th stack consists of aiaiblocks resting on the surface.
The height of the exhibit is equal to mm. Consequently, the number of blocks in each stack is less than or equal to mm.
There is a camera on the ceiling that sees the top view of the blocks and a camera on the right wall that sees the side view of the blocks.
Find the maximum number of blocks you can remove such that the views for both the cameras would not change.
Note, that while originally all blocks are stacked on the floor, it is not required for them to stay connected to the floor after some blocks are removed. There is no gravity in the whole exhibition, so no block would fall down, even if the block underneath is removed. It is not allowed to move blocks by hand either.
Input
The first line contains two integers nn and mm (1≤n≤1000001≤n≤100000, 1≤m≤1091≤m≤109) — the number of stacks and the height of the exhibit.
The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤m1≤ai≤m) — the number of blocks in each stack from left to right.
Output
Print exactly one integer — the maximum number of blocks that can be removed.
Examples
input
Copy
5 6 3 3 3 3 3
output
Copy
10
input
Copy
3 5 1 2 4
output
Copy
3
input
Copy
5 5 2 3 1 4 4
output
Copy
9
input
Copy
1 1000 548
output
Copy
0
input
Copy
3 3 3 1 1
output
Copy
1
Note
The following pictures illustrate the first example and its possible solution.
Blue cells indicate removed blocks. There are 1010 blue cells, so the answer is 1010.
个人比较讨厌模拟,但是签到还是要做,WA了一发之后,发现里面有玄机,不仅每一层要和之前比较,而且还要考虑有可以替换导致影响低层的情况,比较烦。
我用一个lack记录哪一列需要多余的块来补,哪一列有多出来的可以补给后面高的层。
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int N = 1e5 + 5;
ll a[N];
int main()
{
int n, m;
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++)
scanf("%lld", &a[i]);
sort(a + 1, a + n + 1);
ll ans = 0;
a[0] = 0;
int now = 1;
ll lack = 0, exceed = 0;
while (now <= n)
{
int cnt = 1;
while (now + 1 <= n && a[now + 1] == a[now])
now++, cnt++;
ll tmp = max(cnt * 1ll, a[now] - a[now - cnt]);
if (a[now] - a[now - cnt] > cnt)
{
exceed += a[now] - a[now - cnt] - cnt;
}
else
{
lack += cnt - a[now] + a[now - cnt];
if (exceed >= lack)
{
tmp -= lack;
exceed -= lack;
lack = 0;
}
else
{
tmp -= exceed;
lack = 0;
exceed = 0;
}
}
ans += a[now] * cnt - tmp;
//printf("%d %d %lld\n", now, cnt, ans);
now++;
}
printf("%lld\n", ans);
return 0;
}