日志统计(蓝桥杯)

小明维护着一个程序员论坛。现在他收集了一份"点赞"日志,日志共有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

资源约定:
峰值内存消耗(含虚拟机) < 256M
CPU消耗 < 1000ms

请严格按要求输出,不要画蛇添足地打印类似:“请您输入…” 的多余内容。

注意:
main函数需要返回0;
只使用ANSI C/ANSI C++ 标准;
不要调用依赖于编译环境或操作系统的特殊函数。
所有依赖的函数必须明确地在源文件中 #include
不能通过工程设置而省略常用头文件。

提交程序时,注意选择所期望的语言类型和编译器类型。

1、按时间从小到大排序,通过尺取法计算[T, T+D)时间内,不同id收到的点赞数量,判断是否为热帖。

#include<iostream>
#include<vector>
#include<map>
#include<algorithm>
#include<set>
using namespace std;

int N, D, K;
struct H{
	int ts, id;
};
bool cmp(H h1,H h2){
	return h1.ts < h2.ts;
}

int main(){
	std::ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);

	cin >> N >> D >> K;
	//存日志数据
	vector<H> record(N);
	//记录id及其出现的次数
	map<int, int> cnt;
	//读取日志数据
	for (int i = 0; i < N; i++){
		cin >> record[i].ts >> record[i].id;
	}
	//用自定义比较器对vector排序
	sort(record.begin(), record.end(), cmp);

	int j = 0; //向后移动
	set<int> ans; //记录结果id
	for (int i = 0; i < N; i++){ //i是尺取法的起点
		while (j < N&&record[j].ts - record[i].ts < D){
			cnt[record[j].id]++; //该id的计数+1
			if (cnt[record[j].id] >= K)
				ans.insert(record[j].id);
			j++;
		}
		cnt[record[i].id]--;
	}
	for (set<int>::iterator it = ans.begin(); it != ans.end(); it++){
		cout << *it << endl;
	}

	system("pause");
	return 0;
}

将相同id的ts时刻放入一个multiset集合中,通过尺取法计算[T, T+D)时间内,点赞个数,判断是否为热帖。

#include<iostream>
#include<map>
#include<set>
using namespace std;

int N, D, K;

int main(){
	std::ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);

	cin >> N >> D >> K;
	//使用map存储ts,id
	map<int, multiset<int>> col;
	//set存储“热帖”的id
	set<int> ans;
	
	//输入ts,id
	int ts, id;
	for (int i = 0; i < N; i++){
		cin >> ts >> id;
		col[id].insert(ts);
	}

	for (map<int, multiset<int>>::iterator it = col.begin(); it != col.end(); it++){
		multiset<int>::iterator it3 = it->second.begin(); //指向某个id的ts集合
		int num = 0; //某一[T, T+D)时间内,点赞数量
		for (multiset<int>::iterator it2 = it->second.begin(); it2 != it->second.end(); it2++){ //it2是尺取法的起点
			while (it3 != it->second.end() && (*it3) - (*it2) < D){
				num++;
				if (num >= K)
					ans.insert(it->first);
				it3++; //向后移动
			}
			num--; 
		}
	}

	//输出“热帖”的id
	for (set<int>::iterator it = ans.begin(); it != ans.end(); it++){
		cout << *it << endl;
	}

	system("pause");
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值