Bootstrap

算法习题--蓝桥杯

在这里插入图片描述

python

def read_log(filename):
    log = []
    with open(filename, 'r') as file:
        for line in file:
            correct_char, input_char, timestamp = line.split()
            log.append((correct_char, input_char, int(timestamp)))
    return log

def longest_combo(log):
    if len(log) <= 1:
        return len(log)

    max_combo = 1
    current_combo = 1

    for i in range(1, len(log)):
        if log[i][1] == log[i][0] and log[i][2] - log[i - 1][2] <= 1000:
            current_combo += 1
            if current_combo > max_combo:
                max_combo = current_combo
        else:
            current_combo = 1

    return max_combo

if __name__ == "__main__":
    filename = "log.txt"
    log = read_log(filename)
    result = longest_combo(log)
    print(result)

c

#include <stdio.h>
#include <stdlib.h>

// 定义记录结构体
typedef struct {
    char correct_char;
    char input_char;
    long long timestamp;
} LogEntry;

// 读取日志文件
int read_log(const char *filename, LogEntry *log, int *n) {
    FILE *file = fopen(filename, "r");
    if (file == NULL) {
        return -1;
    }

    int count = 0;
    while (fscanf(file, "%c %c %lld\n", &log[count].correct_char, &log[count].input_char, &log[count].timestamp) == 3) {
        count++;
    }

    fclose(file);
    *n = count;
    return 0;
}

// 计算最长连击
int longest_combo(LogEntry *log, int n) {
    if (n <= 1) {
        return n;
    }

    int max_combo = 1;
    int current_combo = 1;

    for (int i = 1; i < n; i++) {
        if (log[i].input_char == log[i].correct_char && log[i].timestamp - log[i - 1].timestamp <= 1000) {
            current_combo++;
            if (current_combo > max_combo) {
                max_combo = current_combo;
            }
        } else {
            current_combo = 1;
        }
    }

    return max_combo;
}

int main() {
    const char *filename = "log.txt";
    LogEntry log[10000]; // 假设最多有10000条记录
    int n;

    if (read_log(filename, log, &n) != 0) {
        fprintf(stderr, "Error reading log file.\n");
        return 1;
    }

    int result = longest_combo(log, n);
    printf("%d\n", result);

    return 0;
}
;