1.暴力做法
#include <iostream>
#include <algorithm>
#include <cstring>
//暴力做法,会超时
using namespace std;
#define x first
#define y second
const int N = 100005;
bool id[N]; //表示一个帖子是否是热帖
typedef pair<int, int> PII;
PII ts[N]; //表示第i个记录发布的时刻
int cnt[N];
int main()
{
int n, D, K;
cin >> n >> D >> K;
for (int i = 1;i <= n;i++)
cin >> ts[i].x >> ts[i].y;
sort(ts, ts + n);
for (int i = 1;i < n;i++)
{
memset(cnt, 0,sizeof(cnt));
for (int j = i;ts[j].x - ts[i].x < D&&j<=n;j++)
{
cnt[ts[j].y]++;
}
for (int j = 0;j < N;j++)
if (cnt[j] >= K)
id[j] = true;
}
for (int i = 0;i < N;i++)
if(id[i])
cout << i<< '\n';
}
2.双指针做法
由于每次都只维护开头和结尾,那么我们只需要一个for循环就可以,这样子时间复杂度是O(N)
但是我们要确保j-i的区间长度有d,所以伪代码需要修改一下
#include <iostream>
#include <algorithm>
#define x first
#define y second
#define ts x
#define id y
using namespace std;
const int N=1e5+10;
typedef pair<int,int> PII;
PII a[N];
bool st[N]; //判断是否是热帖
int cnt[N]; //判断当前区间的赞数
int main()
{
int n,d,k;
cin>>n>>d>>k;
for(int i=0;i<n;i++)
cin>>a[i].x>>a[i].y;
sort(a,a+n);
for(int i=0,j=0;i<n;)
{
while(j<n&&a[j].x-a[i].x<d)
{
//需要进行更新
cnt[a[j].y]++; //赞数+1
if(cnt[a[j].y]==k)
st[a[j].y]=true;
j++;
}
cnt[a[i].y]--;
i++;
}
for(int i=0;i<N;i++)
if(st[i])
cout<<i<<'\n';
return 0;
}
麻烦一点的双指针(上面while缩小窗口,这里的while扩大窗口)
#include <iostream>
#include <algorithm>
#define x first
#define y second
using namespace std;
const int N = 1E5 + 5;
int a[N];
bool st[N];
typedef pair<int, int> PII;
PII w[N];
int main()
{
int n, d, k;
cin >> n >> d >> k;
for (int i = 0;i < n;i++)
cin >> w[i].x >> w[i].y;
sort(w, w + n);
for (int i = 0, j = 0;i < n && j < n;)
{ //i右j左
//让区间滑动到满足条件的大小
while (i<n&&w[i].x - w[j].x < d)
{
a[w[i].y]++;
i++;
}
//缩小区间,判断即将抛弃的点是不是满足
if (a[w[j].y] >= k)
st[w[j].y] = true;
a[w[j].y]--;
j++;
}
for (int i = 0;i < N;i++)
{
if(a[i]>=k)
st[i]=true;
if (st[i])
cout << i << '\n';
}
}