未优化:
先上70分未优化的代码吧
#include<bits/stdc++.h>
using namespace std;
typedef pair<int, int> p;
int n, m, k;
vector<p> a;
int res(int q)
{
int tem = 0;
for (int i = 0; i < a.size(); ++i)
{
if (a[i].first < q + k || a[i].first >= q + k + a[i].second)
{
continue;
}
else tem++;
}
return tem;
}
int main()
{
cin >> n >> m >> k;
for (int i = 1; i <= n; ++i)
{
p t;
cin >> t.first >> t.second;
a.push_back(t);
}
for (int i = 0; i < m; ++i)
{
int q;
cin >> q;
cout << res(q) << endl;
}
return 0;
}
由于对于每个查询q(即做核酸时间),都会遍历n次,时间复杂度在O(m*n),没办法在线性时间内给出答案,因此只能过70分的点
优化:
我们需要改变一下思路
70分时,我们是对人进行的考虑,如果从每个场所考虑,能否进入取决于核酸时间q是否符合条件,即q是否在合格的区间内
只要核酸时间q在这个区间内,就能进入这个场地,因此整个区间都会+1
简略地画了一个草图帮助理解
这里我们就可以想到使用差分数组,完成在O(1)内对于区间的修改
优化代码如下:
#include<bits/stdc++.h>
using namespace std;
typedef pair<int, int> p;
int n, m, k;
vector<int> a(200001);
//差分数组
int main()
{
cin >> n >> m >> k;
for (int i = 0; i < n; ++i)
{
int t, c;
cin >> t >> c;
int le = max(t - k - c + 1, 1);//左区间取大于0的部分
int ri = max(t - k, 0);//右区间
if (ri > 0)//区间右端覆盖大于0才有意义
{
a[le]++;
a[ri + 1]--;
}
}
//前缀和还原数组
for (int i = 1; i < 200001; ++i)
{
a[i] = a[i] + a[i - 1];
}
for (int i = 0; i < m; ++i)
{
int q;
cin >> q;
cout << a[q] << endl;
}
return 0;
}
至此可以拿下剩下30分
一些小问题:
对于区间需要一定的取舍,考虑到(题目中t、q、c>0),左端取大于0的部分(即截去舍弃小于或等于0的部分),同时如果右端都达不到1,整个区间都没有大于0的部分,这个区间也就没有取的必要。
最后:
这道题over,完全忘了咋做,硬做只拿了70,后面想不出来(卒),看了网上的差分数组做法,普遍都是把k拿出来,即t-c+1<=q+k<=t,似乎更方便 一点,虽然我这个也差不太多。实际做题还是没做出来,记录方法思路,想复习一下差分和前缀和。