版本比较
军火库说是
正文
增加 407 行删除 0 行
1,135 行未改动全部展开1136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550138 行未改动全部展开1,135 行未改动全部展开 }})();```::::::info[题目颜色]```js// ==UserScript==// @name 洛谷题目难度着色+标签速览// @namespace https://www.luogu.com.cn/// @version 2.3// @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 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); } }
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'); } }
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;
const childNodes = node.childNodes; for (let i = 0; i < childNodes.length; i++) { colorizeNode(childNodes[i]); } } }
function processTextNode(node) { if (processedTextNodes.has(node)) return; let parent = node.parentNode; while (parent && parent !== document.body) { if (parent.tagName === 'A' && parent.getAttribute('href')?.includes('/problem/')) { return; } parent = parent.parentNode; }
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 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(); } catch (err) { console.error('[洛谷题目着色] 初始化失败:', err); showStatusMessage('题库下载失败,请检查网络后刷新重试', true); startObserver(); } }
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', init); } else { init(); }})();```:::::::::::success[工具]:::info[文本加密&解密]```cpp138 行未改动全部展开