题目:
小明维护着一个程序员论坛。现在他收集了一份"点赞"日志,日志共有N行。其中每一行的格式是:ts id
表示在ts时刻编号id的帖子收到一个"赞"。
现在小明想统计有哪些帖子曾经是"热帖"。如果一个帖子曾在任意一个长度为D的时间段内收到不少于K个赞,小明就认为这个帖子曾是"热帖"。
具体来说,如果存在某个时刻T满足该帖在[T, T+D)这段时间内(注意是左闭右开区间)收到不少于K个赞,该帖就曾是"热帖"。
给定日志,请你帮助小明统计出所有曾是"热帖"的帖子编号。
【输入格式】
第一行包含三个整数N、D和K。
以下N行每行一条日志,包含两个整数ts和id。
对于50%的数据,1 <= K <= N <= 1000
对于100%的数据,1 <= K <= N <= 100000 0 <= ts <= 100000 0 <= id <= 100000
【输出格式】
按从小到大的顺序输出热帖id。每个id一行。
【输入样例】
7 10 2
0 1
0 10
10 10
10 1
9 1
100 3
100 3
【输出样例】
1
3
分析:
在一个不断变化和移动的区间内进行统计,符合尺取法的特点,所以这道题用尺取法来做
在[s, t)区间上满足r[t].ts-r[s].ts < D的前提下,反复的进行:t不断向右扩充,s不断向右缩短
步骤:
1.初始化s = 0,t = 0,set<int> ans;(ans这个集合用来存储满足条件的id号)
2.只要依然有r[t].ts - rs[s].ts < D,就继续向右扩充t++,如果有id号收到>=K个赞的,就加入结果集
3.如果(2)中无法满足 r[t].ts - rs[s].ts < D则终止
4.将cnt[r[s].id]--,s++,然后回到 (2)
代码:
#include<iostream>
#include<map>
#include<set>
#include<algorithm>
using namespace std;
const int MAX_N = 1e5+1;
int N,D,K;
typedef struct record{
int ts;
int id;
}R;
R r[MAX_N];
bool myComp(R& r1,R& r2){
return r1.ts < r2.ts;
}
int main(){
cin >> N >> D >> K;
for(int i = 0;i < N;i++){
cin >> r[i].ts >> r[i].id;
}
sort(r,r+N,myComp);//按时间进行排序
map<int,int> cnt;
int s = 0,t = 0;
set<int> ans;//用来装热帖的id号,set集合自动排序
for(;;){
while(t < N && r[t].ts - r[s].ts < D){
cnt[r[t].id]++;
if(cnt[r[t].id] >= K){
ans.insert(r[t].id);
}
t++;
}
if(r[t].ts - r[s].ts < D){
break;
}
cnt[r[s].id]--;
s++;
}
for(set<int> :: iterator it = ans.begin();it != ans.end();it++){
cout << *it << endl;
}
return 0;
}