熱門文章

2025年10月1日 星期三

ZeroJudge 解題筆記:e984. 連假時在做什麼?有沒有空?可以來打code嗎?

作者:王一哲
日期:2025年10月1日


ZeroJudge 題目連結:e984. 連假時在做什麼?有沒有空?可以來打code嗎?

解題想法


用一個自訂函式 find_lln 找第 k 項的 LunlunNumber。在函式中用一個 deque 儲存待處理的數字,先放入 1 ~ 9,再用一個 while 迴圈,當 que 還有資料繼續執行;在迴圈中每次取出 que 開頭的數字存入 num,計數器 cnt 數量加 1,如果 cnt 等於 k,已經找到答案,回傳 num;如果 cnt 小於 k,取出 num 的個位數 last_digit,計算 last_digit 加減 1、不變、加 1 的數值 next_digit,如果 next_digit 在 1 到 9 之中,將新的數值加入 que 之中。

Python 程式碼


單筆測資,使用時間約為 2 s,記憶體約為 93.2 MB,通過測試。
from collections import deque

def find_lln(k):  # 找第 k 位的 Lunlun Number
    que = deque([i for i in range(1, 10)])  # 待處理的數字,先放入 1 ~ 9
    cnt = 0  # 計數器
    while que:  # 當 que 還有資料繼續執行
        num = que.popleft()  # 取出 que 開頭的數字
        cnt += 1  # 計數器加 1
        if cnt == k:  # 如果是第 k 位
            return num  # 回傳 num 並離開函式
        last_digit = num%10  # 取出個位數
        for delta in (-1, 0, 1):  # 個位數的差值 -1, 0, 1
            next_digit = last_digit + delta  # 下一個個位數值
            if 0 <= next_digit <= 9:  # 如果在 0 ~ 9 之間
                que.append(num*10 + next_digit)  # 新的數值加入 que
    return 0  # 預設的回傳值,理論上不會用到

print(find_lln(int(input())))


C++ 程式碼


使用時間約為 18 ms,記憶體約為 15.9 MB,通過測試。
#include <cstdio>
#include <deque>
typedef long long LL;
using namespace std;

LL find_lln(size_t k) {  // 找第 k 位的 Lunlun Number
    deque<LL> que;  // 待處理的數字,先放入 1 ~ 9
    for(LL i=1; i<10; i++) que.push_back(i);
    size_t cnt = 0;  // 計數器
    LL delta[3] = {-1, 0, 1};
    while(!que.empty()) {  // 當 que 還有資料繼續執行
        LL num = que.front(); que.pop_front();  // 取出 que 開頭的數字
        cnt++;  // 計數器加 1
        if (cnt == k) {  // 如果是第 k 位
            return num;  // 回傳 num 並離開函式
        }
        LL last_digit = num%10;  // 取出個位數
        for(int i=0; i<3; i++) {  // 個位數的差值 -1, 0, 1
            LL next_digit = last_digit + delta[i];  // 下一個個位數值
            if (next_digit >= 0 && next_digit <= 9) {  // 如果在 0 ~ 9 之間
                que.push_back(num*10 + next_digit);  // 新的數值加入 que
            }
        }
    }
    return 0;  // 預設的回傳值,理論上不會用到
}

int main() {
    size_t k; scanf("%lu", &k);
    printf("%lld\n", find_lln(k));
    return 0;
}


沒有留言:

張貼留言