蓝桥杯 日志统计

题目描述
小明维护着一个程序员论坛。现在他收集了一份"点赞"日志,日志共有N行。
其中每一行的格式是:ts id。表示在ts时刻编号id的帖子收到一个"赞"。
现在小明想统计有哪些帖子曾经是"热帖"。
如果一个帖子曾在任意一个长度为D的时间段内收到不少于K个赞,小明就认为这个帖子曾是"热帖"。
具体来说,如果存在某个时刻T满足该帖在[T, T+D)这段时间内(注意是左闭右开区间)收到不少于K个赞,该帖就曾是"热帖"。
给定日志,请你帮助小明统计出所有曾是"热帖"的帖子编号。
输入
第一行包含三个整数N、D和K。
以下N行每行一条日志,包含两个整数ts和id。
1 <= K <= N <= 100000 0 <= ts <= 100000 0 <= id <= 100000
输出
按从小到大的顺序输出热帖id。每个id一行。
样例输入 Copy
7 10 2
0 1
0 10
10 10
10 1
9 1
100 3
100 3
样例输出 Copy
1
3

法1:暴力法,只能AC 38%

思路:暴力解决,将数据存储在一个结构体数组中
接着排序,先按id排后再按照ts排序
判断第i个id是否是热门

代码如下:

#include<iostream>
#include<algorithm>
using namespace std;

struct client{
	int ts;
	int id;
};

bool cmp(client a,client b){
	if(a.id==b.id){
		return a.ts<b.ts;
	}
	return a.id<b.id;
}

client c[1000001];

int main(){
	
	int n,d,k;
	cin>>n>>d>>k;
	
	for(int i=0;i<n;i++){
		cin>>c[i].ts>>c[i].id;
	}
		
	sort(c,c+n,cmp);
	
	int t_id=0,flag=0;
	for(int i=0;i<n;i++){
		
		if(c[i].id==t_id){//寻找过并且已经上过热门 
			continue;
		}
		
		int j=i+1;
		
		while(c[j].ts-c[i].ts<k&&c[j].id==c[i].id){
		//寻找与i相距不超过K的点赞数量	 
			flag++;
			j++;
			if(flag>=k-1){
				t_id=c[i].id;
				cout<<c[i].id<<endl;
				break;
			}
		}
		flag=0; 
	}
	return 0;
}

总结:时间复杂度为O(N^2),复杂度过高。

法二:取尺法:双指针

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
 
int n,d,k;
const int maxn=1e5+5;
vector<int> thing[maxn];

bool judge(int id){
	sort(thing[id].begin(),thing[id].end());//排序
	int start=0,end=0,cnt=0;
	while(start<=end){//当start < end 进行循环
		cnt++;//每次都增加cnt,直至cnt==k
		if(cnt>=k){
			if(thing[id][end]-thing[id][start]<k){//判读是否在k的范围内
				return true;
			}
			else{//如果不在范围内
				start++;//start指针指向下一个
				cnt--;
			}
		}
		end++;
	}
	return false;
}

int main()
{
	cin>>n>>d>>k;
	for(int i=0;i<n;i++)
	{
		int ts,id;
		cin>>ts>>id;
		thing[id].push_back(ts);
	}
 
    for(int id=0;id<100001;id++)
    {
        if(thing[id].size()>=k&&judge(id)){
			cout<<id<<endl;
		}
    }
    return 0;
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值