跳到正文

闲话

洛谷美化油猴插件

DanseSolo约 58 分钟
原文

这是 2026年8月30日 存档的第 3 版,不是当前版本。查看当前版本

文章信息与版本

隐藏题号 & 难度。

INFO
JavaScript
// ==UserScript==
// @name         Luogu 题号+难度 整合工具
// @namespace    http://tampermonkey.net/
// @version      1.2
// @description  题号切换+难度隐藏 整合版,主页面隐藏难度按钮,题库页不干扰
// @author       LTTXiaochuan
// @match        https://www.luogu.com.cn/*
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_registerMenuCommand
// @run-at       document-idle
// ==/UserScript==

(function() {
    'use strict';

    // ====================== 工具函数:页面判断 ======================
    const path = location.pathname;
    const searchParams = new URLSearchParams(location.search);

    // 1. 仅匹配:/problem/Pxxxx 或 /contest/xxx/problem/xxx,排除 /problem/list 等题库页
    const isProblemDetailPage =
        (path.startsWith('/problem/') && !path.includes('/list')) ||
        (path.includes('/contest/') && path.includes('/problem/'));

    // 2. 判断是否为洛谷主页面(根路径 / 或 /?xxx)
    const isHomePage = path === '/' && searchParams.get('pid') === null;

    // ====================== 第一部分:题号切换功能(仅题目详情页执行) ======================
    if (isProblemDetailPage) {
        // 默认隐藏
        let mode = GM_getValue('pid_mode', 'hidden');

        // 核心样式
        const css1 = `
        #pidBtn {
            position: fixed;
            top: 12px;
            right: 12px;
            z-index: 999999;
            background: rgba(0,0,0,0.6);
            color: #fff !important;
            padding: 6px 8px;
            font-size: 12px;
            border-radius: 6px;
            cursor: move;
            user-select: none;
            box-shadow: 0 2px 6px rgba(0,0,0,.4);
            min-width: 120px;
            text-align: center;
            font-family: 'Segoe UI',微软雅黑,sans-serif;
        }
        #pidBtn small { opacity: .8; display:block; font-size:11px; margin-top:2px; color: #fff !important; }
        /* 隐藏题号 */
        body.hidePid .breadcrumb a[href*="P"] { display:none !important; }
        /* 打印只隐藏按钮,不破坏页面 */
        @media print { #pidBtn { display:none !important; } }
        `;
        const style1 = document.createElement('style');
        style1.textContent = css1;
        document.head.appendChild(style1);

        // 执行功能 + 侧栏暴力隐藏
        function run() {
            document.body.classList.toggle('hidePid', mode === 'hidden');

            if(mode === 'hidden'){
                const all = document.getElementsByTagName('*');
                for(let el of all){
                    if(el.textContent.trim() === '题目编号'){
                        const val = el.nextElementSibling || el.parentElement.lastElementChild;
                        if(val && val.textContent.startsWith('P')) val.style.display = 'none';
                    }
                }
            }else{
                const all = document.getElementsByTagName('*');
                for(let el of all){
                    if(el.textContent.trim() === '题目编号'){
                        const val = el.nextElementSibling || el.parentElement.lastElementChild;
                        if(val) val.style.display = '';
                    }
                }
            }

            // 主标题原版逻辑
            const h1 = document.querySelector('h1');
            if(h1){
                if(mode === 'hidden'){ h1._o = h1._o || h1.textContent; h1.textContent = 'LoveFurina'; }
                else { h1._o && (h1.textContent = h1._o); }
            }
            // 文字修改为:隐藏题号/显示题号 + (点击切换)
            const label = mode === 'hidden' ? '隐藏题号' : '显示题号';
            document.getElementById('pidBtn').innerHTML = `<strong>${label}</strong><small>(点击切换)</small>`;
        }

        // 创建按钮
        function btn() {
            const b = document.createElement('div');
            b.id = 'pidBtn';
            const x=GM_getValue('x'), y=GM_getValue('y');
            if(x!=null&&y!=null){
                b.style.left=x+'px';
                b.style.top=y+'px';
                b.style.right='auto';
            }else{
                b.style.bottom = "65px";
                b.style.right = "12px";
                b.style.top = "auto";
            }

            let ox,oy,d=false;
            let isDragged = false;

            b.onmousedown = (e)=>{
                d=true;
                isDragged = false;
                ox=e.clientX-b.offsetLeft;
                oy=e.clientY-b.offsetTop;
                b.style.opacity=0.6;
            };

            document.onmousemove = (e)=>{
                if(!d)return;
                isDragged = true;
                b.style.left=Math.max(0,Math.min(innerWidth-b.offsetWidth,e.clientX-ox))+'px';
                b.style.top=Math.max(0,Math.min(innerHeight-b.offsetHeight,e.clientY-oy))+'px';
            };

            document.onmouseup = ()=>{
                if(!d)return;
                d=false;
                b.style.opacity=1;
                GM_setValue('x',b.offsetLeft);
                GM_setValue('y',b.offsetTop);
            };

            b.onclick = ()=>{
                if(!isDragged){
                    mode=mode==='hidden'?'show':'hidden';
                    GM_setValue('pid_mode',mode);
                    run();
                }
            };

            document.body.appendChild(b);
            run();
        }

        // 标签页标题(仅题目页执行)
        const targetTitle = "芙芙超可爱~";
        function setFurinaTitle() {
            if (document.title !== targetTitle) {
                document.title = targetTitle;
            }
        }
        setInterval(setFurinaTitle, 300);

        // 极速响应:轮询间隔50ms(仅题目页执行)
        setInterval(() => {
            const h1 = document.querySelector('h1');
            if(h1){
                if(mode === 'hidden'){
                    h1._o = h1._o || h1.textContent;
                    h1.textContent = 'LoveFurina';
                } else {
                    h1._o && (h1.textContent = h1._o);
                }
            }
        }, 50);

        // 极速响应:题号隐藏(仅题目页执行)
        setInterval(() => {
            if(mode === 'hidden'){
                const all = document.getElementsByTagName('*');
                for(let el of all){
                    if(el.textContent.trim() === '题目编号'){
                        const val = el.nextElementSibling || el.parentElement.lastElementChild;
                        if(val && val.textContent.startsWith('P')) val.style.display = 'none';
                    }
                }
            }
        }, 50);

        // 启动题号功能(仅题目页执行)
        window.addEventListener('load', ()=>{ btn(); setTimeout(run,300); setTimeout(run,800); });
    }

    // ====================== 第二部分:难度隐藏功能(主页面除外,完全不变) ======================
    if (!isHomePage) { // 主页面不执行难度功能
        const DEFAULT_MODE = GM_getValue('lg_diff_mode', 'hover');
        const selectors = [
            '.l-flex-info-row a[href*="problem/list?difficulty"] span',
            '.difficulty span span',
            '.difficulty span.lfe-caption'
        ];

        const styleId = 'tm-luogu-diff-style';
        const css2 = `
        .tm-diff-hidden, .tm-diff-hover { transition: opacity .15s ease !important; }
        .tm-diff-hidden { opacity: 0 !important; }
        .tm-diff-hover { opacity: 0 !important; }
        .tm-diff-hover:hover { opacity: 1 !important; }
        #tm-luogu-diff-toggle {
            position: fixed;
            bottom: 12px;
            right: 12px;
            z-index: 999999;
            background: rgba(0,0,0,0.6);
            color: #fff !important;
            padding: 6px 8px;
            font-size: 12px;
            border-radius: 6px;
            cursor: move;
            user-select: none;
            box-shadow: 0 2px 6px rgba(0,0,0,.4);
        }
        #tm-luogu-diff-toggle small { opacity: .8; display:block; font-size:11px; margin-top:2px; color: #fff !important; }
        `;

        function injectStyle() {
            if (document.getElementById(styleId)) return;
            const s = document.createElement('style');
            s.id = styleId;
            s.textContent = css2;
            document.head.appendChild(s);
        }

        let currentMode = DEFAULT_MODE;
        function applyToElement(el, mode) {
            el.classList.remove('tm-diff-hidden', 'tm-diff-hover');
            if (mode === 'hidden') el.classList.add('tm-diff-hidden');
            else if (mode === 'hover') el.classList.add('tm-diff-hover');
        }

        function applyModeToAll(mode) {
            const combined = selectors.join(',');
            document.querySelectorAll(combined).forEach(el => applyToElement(el, mode));
        }

        let mo = null;
        function startObserver() {
            if (mo) return;
            mo = new MutationObserver(muts => {
                if (muts.some(m => m.addedNodes && m.addedNodes.length)) {
                    applyModeToAll(currentMode);
                }
            });
            mo.observe(document.body, { childList: true, subtree: true });
        }

        function saveMode(mode) {
            currentMode = mode;
            GM_setValue('lg_diff_mode', mode);
            updateToggleText();
            applyModeToAll(mode);
        }

        function nextMode(m) {
            if (m === 'show') return 'hover';
            if (m === 'hover') return 'hidden';
            return 'show';
        }

        function createToggle() {
            if (document.getElementById('tm-luogu-diff-toggle')) return;
            const btn = document.createElement('div');
            btn.id = 'tm-luogu-diff-toggle';
            btn.title = '点击切换难度显示模式';
            btn.style.minWidth = '120px';
            btn.style.textAlign = 'center';
            btn.style.fontFamily = 'Segoe UI,微软雅黑,sans-serif';

            const savedX = GM_getValue('lg_diff_x', null);
            const savedY = GM_getValue('lg_diff_y', null);
            if (savedX !== null && savedY !== null) {
                btn.style.left = savedX + 'px';
                btn.style.top = savedY + 'px';
                btn.style.right = 'auto';
            }

            btn.addEventListener('click', (e) => {
                if (btn._dragging) return;
                saveMode(nextMode(currentMode));
            });

            makeDraggable(btn);
            document.body.appendChild(btn);
            updateToggleText();
        }

        function updateToggleText() {
            const btn = document.getElementById('tm-luogu-diff-toggle');
            if (!btn) return;
            const label = (currentMode === 'show') ? '显示难度' : (currentMode === 'hover') ? '悬停显示难度' : '隐藏难度';
            btn.innerHTML = ` <strong> ${label} </strong> <small> (点击切换) </small> `;
        }

        // 拖动逻辑
        function makeDraggable(el) {
            let offsetX, offsetY, isDown = false;

            el.addEventListener('mousedown', (e) => {
                isDown = true;
                el._dragging = false;
                offsetX = e.clientX - el.offsetLeft;
                offsetY = e.clientY - el.offsetTop;
                el.style.opacity = "0.6";
                document.addEventListener('mousemove', move);
                document.addEventListener('mouseup', up);
            });

            function move(e) {
                if (!isDown) return;
                el._dragging = true;
                let newLeft = e.clientX - offsetX;
                let newTop = e.clientY - offsetY;

                const maxLeft = window.innerWidth - el.offsetWidth;
                const maxTop = window.innerHeight - el.offsetHeight;
                newLeft = Math.max(0, Math.min(maxLeft, newLeft));
                newTop = Math.max(0, Math.min(maxTop, newTop));

                el.style.left = newLeft + 'px';
                el.style.top = newTop + 'px';
                el.style.right = 'auto';
            }

            function up() {
                if (!isDown) return;
                isDown = false;
                el.style.opacity = "1";
                document.removeEventListener('mousemove', move);
                document.removeEventListener('mouseup', up);
                GM_setValue('lg_diff_x', el.offsetLeft);
                GM_setValue('lg_diff_y', el.offsetTop);
                setTimeout(() => { el._dragging = false; }, 50);
            }
        }

        function init() {
            injectStyle();
            createToggle();
            applyModeToAll(currentMode);
            startObserver();
            window.addEventListener('load', () => setTimeout(() => applyModeToAll(currentMode), 300));
        }

        // 启动难度功能
        init();
    }
})();

预览题目显示难度 & 标签。

INFO
JavaScript
// ==UserScript==
// @name         洛谷题目难度着色+标签速览
// @namespace    https://www.luogu.com.cn/
// @version      2.2
// @description  自动着色洛谷题目编号,悬停显示标签,双击跳转题目;
// @author       Assistant
// @match        https://www.luogu.com.cn/*
// @grant        GM_xmlhttpRequest
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_openInTab
// @connect      cdn.luogu.com.cn
// @require      https://cdn.jsdelivr.net/npm/pako@2.1.0/dist/pako.min.js
// ==/UserScript==

(function() {
    'use strict';

    // 难度颜色映射
    const DIFFICULTY_COLORS = {
        0: '#808080', // 灰色
        1: '#e74c3c', // 红色
        2: '#e67e22', // 橙色
        3: '#f1c40f', // 黄色
        4: '#2ecc71', // 绿色
        5: '#00bcd4', // 青色
        6: '#2196F3', // 蓝色
        7: '#9c3dcf', // 紫色
        8: '#000000'  // 黑色
    };

    const DATA_URL = 'https://cdn.luogu.com.cn/problemset-open/latest.ndjson.gz';
    const DB_NAME = 'LuoguProblemDB';
    const DB_VERSION = 1;
    const STORE_NAME = 'problems';
    const MIN_UPDATE_INTERVAL = 3 * 24 * 60 * 60 * 1000; // 3天(毫秒)

    // 题目编号正则,支持 P, B, CF, SP, AT, UVA 等
    const PID_PATTERN = /\b(?:P|B|CF|SP|AT(?:_[A-Za-z0-9]+)?|UVA)\d+[A-Za-z0-9]*\b/g;

    let problemDataMap = new Map();   // pid -> { difficulty, title, tags, type }
    let processedTextNodes = new WeakSet();
    let processedLinks = new WeakSet();
    let observer = null;
    let tooltip = null;

    // ---------- 提示框 ----------
    function createTooltip() {
        if (tooltip) return;
        tooltip = document.createElement('div');
        tooltip.id = 'luogu-problem-tooltip';
        tooltip.style.cssText = `
            position: fixed;
            z-index: 9999999;
            background: rgba(30, 30, 30, 0.95);
            color: #fff;
            padding: 8px 12px;
            border-radius: 6px;
            font-size: 12px;
            max-width: 300px;
            word-wrap: break-word;
            pointer-events: none;
            display: none;
            box-shadow: 0 2px 8px rgba(0,0,0,0.3);
        `;
        document.body.appendChild(tooltip);
    }

    function showTooltip(x, y, content) {
        createTooltip();
        tooltip.innerHTML = content;
        tooltip.style.display = 'block';
        const rect = tooltip.getBoundingClientRect();
        let left = x + 10;
        let top = y + 10;
        if (left + rect.width > window.innerWidth - 5) left = x - rect.width - 10;
        if (top + rect.height > window.innerHeight - 5) top = y - rect.height - 10;
        tooltip.style.left = left + 'px';
        tooltip.style.top = top + 'px';
    }

    function hideTooltip() {
        if (tooltip) tooltip.style.display = 'none';
    }

    // ---------- 状态提示 ----------
    function showStatusMessage(text, isError = false) {
        const existing = document.getElementById('luogu-problem-status');
        if (existing) existing.remove();
        const div = document.createElement('div');
        div.id = 'luogu-problem-status';
        div.style.cssText = `
            position: fixed; top: 20px; right: 20px;
            background: ${isError ? '#f44336' : '#2196F3'};
            color: white; padding: 8px 16px;
            border-radius: 6px; z-index: 999999;
            font-size: 14px; box-shadow: 0 2px 8px rgba(0,0,0,0.2);
            max-width: 300px; word-wrap: break-word;
        `;
        div.textContent = text;
        document.body.appendChild(div);
        if (!isError) {
            setTimeout(() => { if (div.parentNode) div.remove(); }, 5000);
        }
    }

    // ---------- IndexedDB 操作 ----------
    function openDB() {
        return new Promise((resolve, reject) => {
            const request = indexedDB.open(DB_NAME, DB_VERSION);
            request.onupgradeneeded = (e) => {
                const db = e.target.result;
                if (!db.objectStoreNames.contains(STORE_NAME)) {
                    db.createObjectStore(STORE_NAME, { keyPath: 'pid' });
                }
            };
            request.onsuccess = () => resolve(request.result);
            request.onerror = () => reject(request.error);
        });
    }

    async function getProblemCount() {
        const db = await openDB();
        return new Promise((resolve, reject) => {
            const tx = db.transaction(STORE_NAME, 'readonly');
            const store = tx.objectStore(STORE_NAME);
            const req = store.count();
            req.onsuccess = () => resolve(req.result);
            req.onerror = () => reject(req.error);
        });
    }

    async function clearProblems() {
        const db = await openDB();
        return new Promise((resolve, reject) => {
            const tx = db.transaction(STORE_NAME, 'readwrite');
            const store = tx.objectStore(STORE_NAME);
            const req = store.clear();
            req.onsuccess = () => resolve();
            req.onerror = () => reject(req.error);
        });
    }

    async function bulkInsert(problems) {
        const db = await openDB();
        return new Promise((resolve, reject) => {
            const tx = db.transaction(STORE_NAME, 'readwrite');
            const store = tx.objectStore(STORE_NAME);
            for (const p of problems) {
                store.put(p);
            }
            tx.oncomplete = () => resolve();
            tx.onerror = () => reject(tx.error);
        });
    }

    async function loadProblemDataMap() {
        const db = await openDB();
        return new Promise((resolve, reject) => {
            const tx = db.transaction(STORE_NAME, 'readonly');
            const store = tx.objectStore(STORE_NAME);
            const req = store.getAll();
            req.onsuccess = () => {
                const map = new Map();
                req.result.forEach(item => {
                    map.set(item.pid, {
                        difficulty: item.difficulty,
                        title: item.title || '',
                        tags: item.tags || [],
                        type: item.type || ''
                    });
                });
                resolve(map);
            };
            req.onerror = () => reject(req.error);
        });
    }

    // ---------- 下载题库数据 ----------
    async function downloadAndStoreData(onProgress) {
        if (typeof pako === 'undefined') {
            throw new Error('pako 库未加载,请刷新页面重试。');
        }
        await clearProblems();
        return new Promise((resolve, reject) => {
            GM_xmlhttpRequest({
                method: 'GET',
                url: DATA_URL,
                responseType: 'arraybuffer',
                onload: async (res) => {
                    try {
                        const compressed = new Uint8Array(res.response);
                        const decompressed = pako.ungzip(compressed, { to: 'string' });
                        const lines = decompressed.split('\n').filter(line => line.trim() !== '');
                        const total = lines.length;
                        const batchSize = 1000;
                        let imported = 0;

                        const importBatch = async (start) => {
                            const end = Math.min(start + batchSize, total);
                            const batch = [];
                            for (let i = start; i < end; i++) {
                                try {
                                    const obj = JSON.parse(lines[i]);
                                    batch.push({
                                        pid: obj.pid,
                                        title: obj.title,
                                        difficulty: obj.difficulty,
                                        type: obj.type,
                                        tags: obj.tags || []
                                    });
                                } catch (e) {}
                            }
                            if (batch.length > 0) {
                                await bulkInsert(batch);
                                imported += batch.length;
                                if (onProgress) onProgress(imported, total);
                            }
                            if (end < total) {
                                await importBatch(end);
                            } else {
                                resolve();
                            }
                        };

                        await importBatch(0);
                    } catch (e) {
                        reject(e);
                    }
                },
                onerror: (err) => reject(err)
            });
        });
    }

    // ---------- 工具函数:打开题目页面(新增) ----------
    function openProblemPage(pid) {
        const url = `https://www.luogu.com.cn/problem/${pid}`;
        if (typeof GM_openInTab === 'function') {
            GM_openInTab(url, { active: true, insert: true });
        } else {
            window.open(url, '_blank');
        }
    }

    // ---------- DOM 着色与事件绑定 ----------
    function colorizeNode(node) {
        if (!node) return;
        if (node.nodeType === Node.TEXT_NODE) {
            processTextNode(node);
        } else if (node.nodeType === Node.ELEMENT_NODE) {
            if (node.tagName === 'SCRIPT' || node.tagName === 'STYLE' || node.tagName === 'NOSCRIPT') return;
            if (node.classList && node.classList.contains('lg-diff-color')) return;

            // 处理指向题目的链接
            if (node.tagName === 'A' && node.getAttribute('href')?.includes('/problem/')) {
                processProblemLink(node);
                return;
            }

            const childNodes = node.childNodes;
            for (let i = 0; i < childNodes.length; i++) {
                colorizeNode(childNodes[i]);
            }
        }
    }

    function processTextNode(node) {
        if (processedTextNodes.has(node)) return;
        const text = node.textContent;
        if (!text) return;

        PID_PATTERN.lastIndex = 0;
        const replacements = [];
        let match;
        while ((match = PID_PATTERN.exec(text)) !== null) {
            const pid = match[0];
            const problemData = problemDataMap.get(pid);
            if (problemData) {
                replacements.push({
                    start: match.index,
                    end: PID_PATTERN.lastIndex,
                    pid: pid,
                    difficulty: problemData.difficulty,
                    tags: problemData.tags,
                    title: problemData.title
                });
            }
        }

        if (replacements.length === 0) {
            processedTextNodes.add(node);
            return;
        }

        const fragment = document.createDocumentFragment();
        let lastIndex = 0;
        for (const r of replacements) {
            if (r.start > lastIndex) {
                fragment.appendChild(document.createTextNode(text.substring(lastIndex, r.start)));
            }
            const span = document.createElement('span');
            span.className = 'lg-diff-color';
            span.style.color = DIFFICULTY_COLORS[r.difficulty] || '#808080';
            span.style.fontWeight = 'bold';
            span.textContent = r.pid;
            span.style.cursor = 'pointer';

            span.addEventListener('mouseenter', (e) => {
                const tags = r.tags && r.tags.length ? r.tags.join(', ') : '暂无标签';
                const title = r.title ? `<strong>${r.pid} ${r.title}</strong>` : `<strong>${r.pid}</strong>`;
                showTooltip(e.clientX, e.clientY, `${title}<br>标签:${tags}`);
            });
            span.addEventListener('mousemove', (e) => {
                if (tooltip && tooltip.style.display === 'block') {
                    showTooltip(e.clientX, e.clientY, tooltip.innerHTML);
                }
            });
            span.addEventListener('mouseleave', hideTooltip);

            // 双击打开题目页面(使用新函数)
            span.addEventListener('dblclick', (e) => {
                e.preventDefault();
                e.stopImmediatePropagation();
                openProblemPage(r.pid);
            });

            fragment.appendChild(span);
            lastIndex = r.end;
        }
        if (lastIndex < text.length) {
            fragment.appendChild(document.createTextNode(text.substring(lastIndex)));
        }

        node.parentNode.replaceChild(fragment, node);
        processedTextNodes.add(node);
    }

    function processProblemLink(a) {
        if (processedLinks.has(a)) return;
        const href = a.getAttribute('href');
        const match = href && href.match(/\/problem\/([^/?]+)/);
        if (!match) return;
        const pid = decodeURIComponent(match[1]);
        const data = problemDataMap.get(pid);

        processedLinks.add(a);

        if (data) {
            const color = DIFFICULTY_COLORS[data.difficulty] || '#808080';
            a.style.setProperty('color', color, 'important');
            a.style.fontWeight = 'bold';
        }
        a.style.cursor = 'pointer';

        // 阻止单击默认跳转,让双击事件能够生效
        a.addEventListener('click', (e) => {
            e.preventDefault();
        });

        a.addEventListener('mouseenter', (e) => {
            const tags = data && data.tags && data.tags.length ? data.tags.join(', ') : '暂无标签';
            const title = data && data.title ? `<strong>${pid} ${data.title}</strong>` : `<strong>${pid}</strong>`;
            showTooltip(e.clientX, e.clientY, `${title}<br>标签:${tags}`);
        });
        a.addEventListener('mousemove', (e) => {
            if (tooltip && tooltip.style.display === 'block') {
                showTooltip(e.clientX, e.clientY, tooltip.innerHTML);
            }
        });
        a.addEventListener('mouseleave', hideTooltip);

        // 双击打开新页面(使用新函数)
        a.addEventListener('dblclick', (e) => {
            e.preventDefault();
            e.stopImmediatePropagation();
            openProblemPage(pid);
        });
    }

    function colorizeExistingDOM() {
        colorizeNode(document.body);
    }

    function startObserver() {
        if (observer) observer.disconnect();
        observer = new MutationObserver((mutations) => {
            mutations.forEach((mutation) => {
                mutation.addedNodes.forEach((node) => {
                    colorizeNode(node);
                });
            });
        });
        observer.observe(document.body, { childList: true, subtree: true });
    }

    // ---------- 初始化 ----------
    async function init() {
        try {
            const lastUpdate = GM_getValue('last_update_time', 0);
            const now = Date.now();

            let count = await getProblemCount();

            if (count === 0) {
                showStatusMessage('正在下载洛谷题库数据,首次使用可能需要几十秒...');
                console.log('[洛谷题目着色] 无本地题库,开始下载...');
                await downloadAndStoreData((current, total) => {
                    if (current % 5000 === 0 || current === total) {
                        showStatusMessage(`题库下载中: ${current}/${total}`);
                    }
                });
                GM_setValue('last_update_time', Date.now());
                showStatusMessage('题库下载完成,正在着色...');
                console.log('[洛谷题目着色] 下载完成');
            } else if (now - lastUpdate >= MIN_UPDATE_INTERVAL) {
                showStatusMessage('题库数据已超过3天未更新,正在更新...');
                console.log('[洛谷题目着色] 超过3天,开始更新题库...');
                await downloadAndStoreData((current, total) => {
                    if (current % 5000 === 0 || current === total) {
                        showStatusMessage(`题库更新中: ${current}/${total}`);
                    }
                });
                GM_setValue('last_update_time', Date.now());
                showStatusMessage('题库更新完成,正在着色...');
            } else {
                console.log('[洛谷题目着色] 题库数据在3天内已更新过,使用本地缓存');
            }

            problemDataMap = await loadProblemDataMap();
            console.log(`[洛谷题目着色] 已加载 ${problemDataMap.size} 条题目数据`);
            colorizeExistingDOM();
            startObserver();
            showStatusMessage('题目难度着色与标签速览已启用', false);
        } catch (err) {
            console.error('[洛谷题目着色] 初始化失败:', err);
            showStatusMessage('题库下载失败,请检查网络后刷新重试', true);
            startObserver();
        }
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();