1 条题解

  • 0
    @ 2025-4-8 20:58:45

    解题思路

    本题可通过模拟行驶过程来计算行驶距离。记录每次速度变化的时间和速度,当遇到查询时,根据之前的速度和时间间隔计算行驶距离。核心公式为 (distance = speed \times time)。

    实现步骤

    读取输入,判断是速度变化还是查询。若为速度变化,记录新速度和时间。若为查询,计算从上次速度变化到当前查询时刻的行驶距离,并累加到总距离中,然后输出结果。

    代码

    #include <iostream>
    #include <iomanip>
    #include <string>
    #include <sstream>
    
    // 将时间字符串转换为秒数
    int timeToSeconds(const std::string& time) {
        int h, m, s;
        sscanf(time.c_str(), "%d:%d:%d", &h, &m, &s);
        return h * 3600 + m * 60 + s;
    }
    
    int main() {
        std::string line;
        int prevTime = 0;
        int currentSpeed = 0;
        double totalDistance = 0;
    
        while (std::getline(std::cin, line)) {
            std::istringstream iss(line);
            std::string timeStr;
            iss >> timeStr;
            int currentTime = timeToSeconds(timeStr);
    
            int newSpeed;
            if (iss >> newSpeed) {
                // 速度变化
                totalDistance += currentSpeed * (currentTime - prevTime) / 3600.0;
                currentSpeed = newSpeed;
                prevTime = currentTime;
            } else {
                // 查询
                totalDistance += currentSpeed * (currentTime - prevTime) / 3600.0;
                prevTime = currentTime;
                std::cout << timeStr << " " << std::fixed << std::setprecision(2) << totalDistance << " km" << std::endl;
            }
        }
    
        return 0;
    }    
    
    • 1

    信息

    ID
    1501
    时间
    1000ms
    内存
    256MiB
    难度
    10
    标签
    递交数
    2
    已通过
    1
    上传者