前言
因为想试一下链表,但是写的时候发现用将head赋值给临时节点,再用临时节点指向新的节点,结果使用head遍历链表的时候根本就没有指向新节点,然后越改越乱,思绪完全乱了,想请教一下有没有大佬知道是为什么
标题:日志统计
小明维护着一个程序员论坛。现在他收集了一份"点赞"日志,日志共有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
代码
#include <stdio.h>
#include <stdlib.h>
//点赞日志
typedef struct likes_log{
int id;
int ts[100000];
int cnt;
struct likes_log *next;
}log;
//判断id是否为热帖
int hot_topic (log *a,int d,int k) {
int cnt = 0;
for (int i = 0;i < a->cnt;i++) {
for (int j = 0;j <a->cnt;j++) {
if (a->ts[j] - a->ts[i] <= d) {
cnt++;
}
else break;
}
}
if (cnt >= k) {
return 1;
}
else {return 0;
}
}
int main () {
//输入n,d,k
int n,d,k;
scanf ("%d %d %d",&n,&d,&k);
int ts[100000],id[100000];
//输入n个时间以及对应的id
for (int i = 0;i < n;i++) {
scanf ("%d %d",&ts[i],&id[i]);
}
//用第一个节点储存第一个id
log *head = NULL;
//将不同的id按顺序储存在链表中
for (int i = 0;i < n;i++) {
log *nail = (log*)malloc(sizeof(log));
nail->id = id[i];
nail->ts[0] = ts[i];
nail->cnt = 1;
nail->next = NULL;
log *temp = (log*)malloc(sizeof(log));
temp = head;
int flag = 1;
//遍历已有链表,查找有无相同id
if (!temp) {
temp = nail;
}
else {
while (temp->next) {
temp = temp->next;
if (temp->id == id[i]) {
flag = 0;
temp->ts[temp->cnt] = ts[i];
temp->cnt++;
for (int j = 0;j < temp->cnt -1;j++) {
for (int k = 0;k <temp->cnt - 1 - j;k++) {
if (temp->ts[k] > temp->ts[k+1]) {
int t = temp->ts[k];
temp->ts[k] = temp->ts[k+1];
temp->ts[k+1] = t;
}
}
}
}
}
}
//无重复id则新建节点
if (flag) {
temp->next = nail;
printf (" %d ",temp->id);
}
}
int htopic[100000];
int cnt = 0;
//统计是热帖的id
do {
if (hot_topic (head,d,k)) {
htopic[cnt] = head->id;
cnt++;
}
head = head->next;
}
while (head);
for (int i = 0;i <cnt - 1;i++) {
for (int j =0;j < cnt -1-i;j++) {
if (htopic[j] > htopic[j+1]) {
int t = htopic[j];
htopic[j] = htopic[j+1];
htopic[j+1] = t;
}
}
}
for (int i = 0;i < cnt;i++) {
printf ("\n%d\n",htopic[i]);
}
}