小明维护着一个程序员论坛。现在他收集了一份"点赞"日志,日志共有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
解题思路1:
思路:把每个日志获得的点赞信息存储好,按时间排序,用尺取法r在前l在后,
当点赞数大于等于k,判断时间间隔,
不满足就l往前取,r继续往后取,直到点赞数大于等于k执行相同判断.
#include<bits/stdc++.h>
#define mod 1000000007
using namespace std;
typedef long long ll;
const int maxn = 1e5+5;
const double esp = 1e-7;
int n,d,k;
vector<int> t[maxn];
int ans[maxn];
bool judge(int x){
int len = t[x].size();
if(len < k){
return 0;
}
sort(t[x].begin(),t[x].end());
int l = 0,r = 0,sum = 0;//l在左边 r在右边 r小于
while(l <= r && r < len){ //1: 0 9 10
sum++;
if(sum >= k){
if(t[x][r] - t[x][l] < d)//注意是小于
return 1;
else
l++,sum--;
}
r++;
}
return 0;
}
int main(){
cin >> n >> d >> k;
for(int i = 1;i<= n;i++){
int ts,id;
cin >> ts >> id;
t[id].push_back(ts);
}
int cnt = 0;
for(int i = 1;i< maxn;i++){
if(judge(i)){
ans[++cnt] = i;
}
}
for(int i = 1;i<= cnt;i++){
cout << ans[i] << endl;
}
return 0;
}
用vector数组来记录每个id的ts,用set来记录出现过的id(因为set可以自送除重)。对每个id的ts进行排序,先从下标0作左端点开始,向右搜索,如果点赞数大于等于k,但是区间不小于d(左闭右开区间所以区间长度小于d),那么就向右移一次起始端点,这样就避免了重复循环。
#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<set>
using namespace std;
const int N = 100005;
vector<int> t[N];
set<int> s;
int n,d,k;
bool judge(int x){
int len = t[x].size();
if(len < k){
return 0;
}
sort(t[x].begin(),t[x].end());
int l = 0,r = 0,sum = 0;
while(l <= r && r < len){
sum++;
if(sum >= k){
if(t[x][r] - t[x][l] < d){
return 1;
}else{
l++;
sum--;
}
}
r++;
}
return 0;
}
int main(){
cin >> n >> d >> k;
for(int i = 0;i < n;i++){
int ts,id;
cin >> ts >> id;
t[id].push_back(ts);
s.insert(id);
}
int cnt = 0;
for (set<int>::iterator it = s.begin();it != s.end(); it++){//获得set容器内迭代器指向set容器第一个元素,然后依次指向后面的元素
int x = *it;//通过*it访问set里的元素
if(judge(x)){//如果一个帖子是热帖,则输出
printf("%d\n", x);
}
}
return 0;
}