解题思路
避雷针共有 个,雷有 枚,被劈中的避雷针有几个?
当然,朴素的想法是依次枚举每个避雷针,看它是否被劈中,这样的复杂度显然是 的,不过显然这样肯定是过不了的。不过,通过逐一模拟样例,可以发现这样的算法实际上过于复杂了,有很多情况是浪费时间的,实际上只有很少的避雷针会被劈中。
注意到避雷针的编号是连续的整数,我们考虑开一个数组 cnt 表示每个避雷针被劈中的次数。遍历每颗雷,根据题意,将 a_i-2 至 a_i+2 这五个数中在范围 [1, n] 内的数的 cnt 值加 即可。
最后遍历一遍 cnt 数组,如果某个避雷针被劈中了至少一次,答案加 即可。
至此,时间复杂度降到了 ,可以通过本题了。
算法1
(暴力枚举)
对于每颗雷,枚举范围内的避雷针,判断是否被劈中。
算法2
(优化枚举)
只枚举范围内被劈中的避雷针。
时间复杂度
参考文献
C++ 代码
#include <iostream>
using namespace std;
int cnt[1000005];
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m, a;
cin >> n >> m;
while (m--) {
cin >> a;
if (a - 2 >= 1) cnt[a - 2]++;
if (a - 1 >= 1) cnt[a - 1]++;
if (a + 1 <= n) cnt[a + 1]++;
if (a + 2 <= n) cnt[a + 2]++;
cnt[a]++;
}
int ans = 0;
for (int i = 1; i <= n; i++) {
if (cnt[i]) ans++;
}
cout << ans << '\n';
return 0;
}