跳到正文

科技·工程

专业代码解题记录:P1720

Glacyend约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年7月31日
收录
2025年12月12日
更新
2026年10月28日
篇幅
约 3 分钟

版本

  1. v1当前

《专业代码解题记录》系列记录我“闭关修炼”后重回洛谷从简到难所解决的问题的专业级 C++ 和 Rust 代码的记录,来给大家开开眼。

题目:P1720

C++ 专业代码(用时 18ms,内存占用 680.00KB):

C++
#include <cstdint>
#include <iostream>
#include <tuple>

using uint32 = std::uint32_t;
using uint64 = std::uint64_t;

uint64 fibonacci(uint32 n);

int main() {
    std::cin.tie(nullptr);
    std::ios_base::sync_with_stdio(false);

    uint32 n;
    std::cin >> n;

    std::cout << fibonacci(n) << ".00" << std::endl;

    return 0;
}

uint64 fibonacci(const uint32 n) {
    if (n == 0) {
        return 0;
    }
    if (n == 1) {
        return 1;
    }
    uint64 first = 1;
    uint64 second = 1;
    for (uint32 i = 2; i <= n; i++) {
        std::tie(first, second) = std::make_tuple(second, first + second);
    }
    return first;
}

Rust 专业级代码(用时 15ms,内存占用 680.00KB):

Rust
use std::io;

fn main() {
    let mut line = String::new();
    io::stdin().read_line(&mut line).unwrap();
    let n: u32 = line.trim().parse().unwrap();

    println!("{}.00", fibonacci(n));
}

fn fibonacci(n: u32) -> u64 {
    if n == 0 {
        0
    } else if n == 1 {
        1
    } else {
        let mut first = 1;
        let mut second = 1;
        for _ in 2..=n {
            (first, second) = (second, first + second);
        }
        first
    }
}
原文