正文
增加 4386 行删除 508 行
1,887 行未改动全部展开188818891890189118921893189418951896189718981899190019011902190319043 行未改动190819091910191119121913191419158 行未改动192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239221 行未改动24142415241624172418241924202421242224232424242524262427279 行未改动全部展开2707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272923 行未改动27532754275527562757275827592760276127622763276427652766276727682769277027712772190 行未改动全部展开29632964296529662967296829692970297113 行未改动2985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301334 行未改动3048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309126 行未改动3118311931203121312231233124312531263127312831293130313131323133313431353136142 行未改动全部展开32793280328132823283328432853286328740 行未改动3328332933303331333233333334333562 行未改动33983399340034011,887 行未改动全部展开*/// ==UserScript==// @name 洛谷随机跳题(离线)// @namespace http://tampermonkey.net/// @version 2.0// @description 筛选题库、难度、标签后随机跳题,使用离线题库// @author karsl// @match https://www.luogu.com.cn/// @icon https://www.luogu.com.cn/favicon.ico// @grant GM_xmlhttpRequest// @connect www.luogu.com.cn// @connect cdn.luogu.com.cn// @require https://cdn.jsdelivr.net/npm/pako@2.1.0/dist/pako.min.js// ==/UserScript==(function() {'use strict';3 行未改动const STORE_NAME = 'problems';const METADATA_STORE = 'metadata';const USER_STATUS_STORE = 'user_status';const DATA_URL = 'https://cdn.luogu.com.cn/problemset-open/latest.ndjson.gz';const DIFFICULTY_MAP = {0: '暂未评定',1: '入门',8 行未改动const TYPE_MAP = {'洛谷': 'luogu','主题库': 'P','入门与面试': 'B','Codeforces': 'CF','SPOJ': 'SP','AtCoder': 'AT','UVa': 'UVA'};const TYPE_KEYS = Object.keys(TYPE_MAP);const dimensionMaps = {algorithm: {'语言入门': '-2','字符串': '2','后缀自动机 SAM': '101','字典树 Trie': '300','AC 自动机': '301','KMP 算法': '302','后缀数组 SA': '303','后缀树': '304','有限状态自动机': '305','回文自动机 PAM': '325','Manacher 算法': '329','顺序结构': '353','分支结构': '354','循环结构': '355','数组': '356','字符串(入门)': '357','结构体': '358','函数与递归': '359','Lyndon 分解': '419','Z 函数': '474','动态规划 DP': '3','搜索': '4','广度优先搜索 BFS': '126','深度优先搜索 DFS': '127','剪枝': '128','记忆化搜索': '129','启发式搜索': '130','迭代加深搜索': '131','启发式迭代加深搜索 IDA*': '132','Dancing Links': '133','爬山算法 Local search': '134','模拟退火': '135','背包 DP': '139','数位 DP': '141','区间 DP': '144','树形 DP': '152','轮廓线 DP': '323','线性 DP': '444','状压 DP': '464','后缀平衡树': '496','数学': '5','图论': '6','Kruskal 重构树': '68','网络流': '79','信息论': '122','随机调整': '136','遗传算法': '137','图论建模': '155','图遍历': '158','拓扑排序': '159','最短路': '160','生成树': '166','平面图': '172','最小环': '173','A* 算法': '263','折半搜索 meet in the middle': '380','梯度下降法': '396','拉格朗日乘数法': '412','拉格朗日插值法': '417','单位根反演': '480','负权环': '174','连通块': '175','2-SAT': '176','平面图欧拉公式': '177','强连通分量': '179','Tarjan': '180','双连通分量': '181','欧拉回路': '182','差分约束': '185','仙人掌': '186','二分图': '187','一般图的最大匹配': '189','上下界网络流': '197','最小割': '198','费用流': '204','圆方树': '350','弦图': '450','Floyd 算法': '476','广义串并联图': '530','Hall 定理': '541','计算几何': '8','树形数据结构': '11','线段树': '42','并查集': '47','平衡树': '50','堆': '51','树状数组': '53','cdq 分治': '100','可并堆': '215','动态树 LCT': '229','三维计算几何': '283','向量': '286','凸包': '291','叉积': '292','线段相交': '293','半平面交': '295','旋转卡壳': '299','极角排序': '449','平面几何': '482','闵可夫斯基和 Minkowski sum': '525','博弈论': '13','线性数据结构': '44','单调队列': '56','颜色段均摊(珂朵莉树 ODT)': '65','树套树': '232','可持久化线段树': '233','可持久化': '234','前缀和': '254','栈': '287','队列': '288','博弈树': '311','整体二分': '316','K-D Tree': '321','Nim 积': '370','李超线段树': '377','吉司机线段树 segment tree beats': '378','线段树合并': '379','SG 函数': '445','二区间合并(猫树分治)': '531','KTT / Kinetic Tournament Tree': '539','原根': '66','多项式': '69','数论': '72','素数判断': '239','最大公约数 gcd': '241','扩展欧几里德算法': '242','不定方程': '243','进制': '244','分块': '289','ST 表': '290','快速傅里叶变换 FFT': '313','快速数论变换 NTT': '324','快速沃尔什变换 FWT': '326','快速莫比乌斯变换 FMT': '327','差分': '330','链表': '360','单调栈': '385','Berlekamp-Massey(BM) 算法': '391','集合幂级数,子集卷积': '416','哈希表': '473','模拟': '1','贪心': '7','基础算法': '110','中国剩余定理 CRT': '250','莫比乌斯反演': '251','逆元': '276','Lucas 定理': '322','类欧几里得算法': '388','调和级数': '411','欧拉降幂': '415','Stern-Brocot 树': '423','整除分块': '448','Dirichlet 卷积': '451','大步小步算法 BSGS': '452','二次剩余': '453','Bézout 定理': '455','杜教筛': '461','欧拉函数': '462','线性筛法': '475','亚线性快速求和算法': '540','递推': '12','倍增': '43','二分': '45','递归': '54','枚举': '111','分治': '112','排序': '113','动态规划优化': '146','优先队列': '148','矩阵加速': '149','斜率优化': '150','状态合并': '151','凸完全单调性(wqs 二分)': '153','四边形不等式': '154','DP 套 DP': '435','动态 DP': '443','决策单调性': '463','STL': '504','整体转移': '507','斜率维护技巧 slope trick': '508','点分治': '49','树上启发式合并': '55','树的遍历': '208','最近公共祖先 LCA': '211','树的直径': '213','树链剖分': '228','树论': '230','群论': '246','置换': '247','Pólya 定理': '248','虚树': '249','组合数学': '252','排列组合': '253','二项式定理': '255','康托展开': '256','基环树': '320','动态树分治': '382','Prüfer 序列': '410','全局平衡二叉树': '472','树的重心': '483','LGV 引理': '63','矩阵树定理': '64','矩阵运算': '71','鸽笼原理': '258','容斥原理': '259','Fibonacci 数列': '260','Catalan 数': '261','Stirling 数': '262','生成函数': '264','概率论': '266','期望': '270','线性代数': '271','矩阵乘法': '272','线性递推': '273','高斯消元': '274','Dilworth 定理': '364','拉格朗日反演': '372','杨表': '387','随机游走 Markov Chain': '457','鞅的停时定理': '458','暴力数据结构': '9','高精度': '10','莫队': '41','三分': '67','离散化': '78','霍夫曼树': '214','哈希 hashing': '235','线性基': '277','微积分': '278','导数': '280','积分': '281','定积分': '282','级数': '284','扫描线': '298','其它技巧': '308','随机化': '309','位运算': '314','构造': '318','行列式': '454','特征值': '466','分数规划': '202','线性规划': '265','双指针 two-pointer': '345','Ad-hoc': '365','笛卡尔树': '368','拟阵': '369','根号分治': '371','模拟费用流': '373','分散层叠': '374','均摊分析': '375','分类讨论': '376','近似算法': '413','线段树分治': '446','离线处理': '447','bitset': '465','组合优化': '467','整数规划': '468','原始对偶': '470','启发式合并': '477','反悔贪心': '524','最大流最小割定理': '471','保序回归': '484'},source: {'各省省选': '48','集训队互测': '52','福建省历届夏令营': '70','NOI': '77','NOIP 普及组': '82','NOIP 提高组': '83','APIO': '85','NOI 导刊': '99','CTT(清华集训/北大集训)': '331','网络流与线性规划 24 题': '332','CSP-S 提高级': '342','CSP-J 入门级': '343','NOI Online': '347','Ynoi': '348','NOI 系列赛事': '426','经典套题': '427','国际知名赛事': '428','WC': '459','CTSC/CTS': '460','模板题': '523','USACO': '46','POI(波兰)': '57','IOI': '102','CCO(加拿大)': '115','CCC(加拿大)': '116','CEOI(中欧)': '117','eJOI(欧洲)': '118','COCI(克罗地亚)': '333','BalticOI(波罗的海)': '334','JOI(日本)': '336','AGM': '346','PA(波兰)': '389','ROI(俄罗斯)': '393','EGOI(欧洲/女生)': '394','NOISG(新加坡)': '436','NordicOI(北欧)': '437','BalkanOI(巴尔干半岛)': '439','KOI(韩国)': '440','RMI(罗马尼亚)': '441','COI(克罗地亚)': '478','洛谷原创': '81','ICPC': '335','洛谷月赛': '337','语言月赛': '386','洛谷比赛': '429','大学竞赛': '430','ROIR(俄罗斯)': '479','INOI(伊朗)': '505','UOI(乌克兰)': '506','JOISC/JOIST(日本)': '512','COTS(克罗地亚)': '513','Google Code Jam': '514','Moscow Olympiad': '515','PO(瑞典)': '518','PAIO': '519','MCC/MCO(马来西亚)': '533','KTSC(韩国)': '535','IATI(保加利亚/东欧)': '537','Google Kick Start': '538','入门赛': '542','蓝桥杯国赛': '361','蓝桥杯省赛': '363','省赛/邀请赛': '381','传智杯': '383','THUPC': '390','GESP': '409','其他竞赛': '431','THUSC': '432','高校校赛': '434','THUWC': '438','CSP-X 小学组': '442','Code+': '485','梦熊比赛': '486','信息与未来': '487','科创活动': '488','BCSP-X': '489','小学活动': '492','初中活动': '493','CSPro': '516','CCPC': '526','科大国创杯': '494','蓝桥杯青少年组': '495'},time: {'1996': '344','1997': '14','1998': '15','1999': '16','2000': '17','2001': '18','2002': '19','2003': '20','2004': '21','2005': '22','2006': '23','2007': '24','2008': '25','2009': '26','2010': '27','2011': '28','2012': '29','2013': '30','2014': '31','2015': '32','2016': '33','2017': '34','2018': '35','2019': '36','2020': '37','2021': '58','2022': '59','2023': '60','2024': '61','2025': '62','2026': '338','2027': '339','2028': '340','2029': '367','2077': '341','2078': '362','2079': '424'},region: {'重庆': '38','四川': '39','河南': '40','浙江': '88','上海': '89','福建': '90','江苏': '91','安徽': '92','湖南': '93','北京': '94','河北': '95','广东': '96','山东': '97','吉林': '98','山西': '114','江西': '161','贵州': '162','广西': '163','陕西': '164','国内省市': '497','辽宁': '167','云南': '168','天津': '328','湖北': '397','黑龙江': '398','海南': '399','甘肃': '400','青海': '401','台湾': '402','内蒙古': '403','西藏': '404','宁夏': '405','新疆': '406','香港': '407','澳门': '408','济南': '420','南京': '421','青岛': '422','国内赛站': '498','EC Final': '509','国际赛区': '499','NERC/NEERC': '500','SEERC': '501','CERC': '502','NWRRC': '503','WF': '510','NAC': '511','杭州': '520','昆明': '521','西安': '522','哈尔滨': '527','首尔': '528','横浜': '529','SWERC': '532','成都': '534','雅加达': '536'},special: {'交互题': '103','提交答案': '104','Special Judge': '107','O2优化': '108','通信题': '351'}};const DIMENSION_NAMES = {algorithm: '算法',21 行未改动let acceptedSet = new Set();let submittedSet = new Set();let userStatusReady = false;function loadSettings() {try {const raw = localStorage.getItem(STORAGE_KEY);if (!raw) return;const data = JSON.parse(raw);if (data.types) selectedTypes = new Set(data.types);if (data.difficulties) selectedDifficulties = new Set(data.difficulties);if (data.tags) {DIMENSION_KEYS.forEach(key => {if (data.tags[key] && Array.isArray(data.tags[key])) {279 行未改动全部展开}if (filters.tags) {const tagNames = [];DIMENSION_KEYS.forEach(key => {const ids = filters.tags[key] || new Set();const map = dimensionMaps[key] || {};for (const id of ids) {for (const [name, val] of Object.entries(map)) {if (val === id) {tagNames.push(name);break;}}}});if (tagNames.length > 0) {results = results.filter(p => {if (!p.tags || p.tags.length === 0) return false;return p.tags.some(t => tagNames.includes(t));});}}23 行未改动function createFloatingPanel(button) {const panel = document.createElement('div');panel.style.cssText = `position: absolute;bottom: calc(100% + 10px);right: 0;background: #fff;border-radius: 12px;box-shadow: 0 8px 24px rgba(0,0,0,0.08);padding: 16px 18px;width: 300px;max-height: 480px;overflow-y: auto;border: 1px solid #eee;z-index: 10000;display: none;font-size: 13px;line-height: 1.5;color: #333;190 行未改动全部展开panel.appendChild(actionContainer);DIMENSION_KEYS.forEach(dimKey => {const dimName = DIMENSION_NAMES[dimKey] || dimKey;const map = dimensionMaps[dimKey] || {};const tagSet = selectedTags[dimKey];const section = document.createElement('div');section.style.cssText = 'margin-bottom:14px;';13 行未改动selectedContainer.style.display = 'none';return;}selectedContainer.style.display = 'flex';tagSet.forEach(tagId => {let name = null;for (const [n, id] of Object.entries(map)) {if (id === tagId) { name = n; break; }}const displayName = name || `ID:${tagId}`;const tagEl = document.createElement('span');tagEl.style.cssText = `display:inline-flex; align-items:center;background:#eef3ff; color:#2b5cd9;padding:2px 10px; border-radius:14px;font-size:11px; gap:4px;`;const nameSpan = document.createElement('span');nameSpan.textContent = displayName;const removeBtn = document.createElement('span');removeBtn.textContent = '×';removeBtn.style.cssText = 'cursor:pointer; font-weight:700; color:#7a8bb0; font-size:14px;';removeBtn.onclick = (e) => {e.stopPropagation();tagSet.delete(tagId);updateSelectedDisplay();saveSettings();};tagEl.appendChild(nameSpan);34 行未改动input.addEventListener('input', function() {const query = this.value.trim().toLowerCase();if (!query) { suggestionBox.style.display = 'none'; return; }const matches = [];for (const [name, id] of Object.entries(map)) {if (name.toLowerCase().includes(query)) {if (!matches.some(m => m.id === id)) {matches.push({ id, name });}}}if (matches.length === 0) { suggestionBox.style.display = 'none'; return; }suggestionBox.innerHTML = '';matches.slice(0, 10).forEach(({ id, name }) => {const item = document.createElement('div');item.style.cssText = `padding:3px 10px; cursor:pointer; font-size:12px;border-bottom:1px solid #f5f5f5;display:flex; justify-content:space-between;transition:background 0.1s;`;item.onmouseenter = () => { item.style.background = '#f5f7fa'; };item.onmouseleave = () => { item.style.background = 'transparent'; };item.addEventListener('mousedown', function(e) { e.preventDefault(); });item.onclick = () => {if (!tagSet.has(id)) {tagSet.add(id);updateSelectedDisplay();saveSettings();}input.value = '';suggestionBox.style.display = 'none';};const nameSpan = document.createElement('span');nameSpan.textContent = name;const idSpan = document.createElement('span');idSpan.textContent = `ID:${id}`;idSpan.style.cssText = 'color:#aaa; font-size:10px;';item.appendChild(nameSpan);item.appendChild(idSpan);suggestionBox.appendChild(item);});suggestionBox.style.display = 'block';});26 行未改动let hoverTimeout = null;button.addEventListener('mouseenter', function() {clearTimeout(hoverTimeout);panel.style.display = 'block';requestAnimationFrame(() => {const rect = button.getBoundingClientRect();const panelRect = panel.getBoundingClientRect();if (rect.top - panelRect.height < 10) {panel.style.bottom = 'auto';panel.style.top = 'calc(100% + 10px)';} else {panel.style.bottom = 'calc(100% + 10px)';panel.style.top = 'auto';}});});button.addEventListener('mouseleave', function(e) {hoverTimeout = setTimeout(() => {142 行未改动全部展开difficulty: obj.difficulty,type: obj.type,tags: obj.tags || []});} catch (e) { /* ignore */ }}if (batch.length === 0) {if (end < total) importBatch(end);else resolve();40 行未改动async function initCore() {setupUI();console.log('【洛谷随机跳题】UI 已创建,等待用户状态初始化...');waitForUid().then(async (uid) => {if (uid) {const success = await initUserStatus(uid);if (success) {62 行未改动}})();```:::1,887 行未改动全部展开1888188918901891189218931894189518961897189818991900190119021903190419051906190719083 行未改动19121913191419151916191719181919192019218 行未改动19301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239421 行未改动241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589279 行未改动全部展开28692870287128722873287428752876287728782879288028812882288323 行未改动290729082909291029112912291329142915291629172918291929202921292229232924190 行未改动全部展开31153116311731183119312031213122312313 行未改动31373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316034 行未改动31953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323326 行未改动3260326132623263326432653266326732683269327032713272327332743275327632773278327932803281142 行未改动全部展开34243425342634273428342934303431343240 行未改动347334743475347634773478347934803481348262 行未改动3545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872791,887 行未改动全部展开*/// ==UserScript==// @name 洛谷随机跳题(离线)// @namespace http://tampermonkey.net/// @version 2.8// @description 筛选题库、难度、标签后随机跳题,使用离线题库// @author karsl// @match https://www.luogu.com.cn/// @icon https://www.luogu.com.cn/favicon.ico// @grant GM_xmlhttpRequest// @grant GM_info// @connect www.luogu.com.cn// @connect cdn.luogu.com.cn// @connect raw.githubusercontent.com// @require https://cdn.jsdelivr.net/npm/pako@2.1.0/dist/pako.min.js// @downloadURL https://raw.githubusercontent.com/karsl-program/LRJPP/main/main.user.js// @updateURL https://raw.githubusercontent.com/karsl-program/LRJPP/main/main.user.js// ==/UserScript==(function() {'use strict';3 行未改动const STORE_NAME = 'problems';const METADATA_STORE = 'metadata';const USER_STATUS_STORE = 'user_status';const DATA_URL = 'https://cdn.luogu.com.cn/problemset-open/latest.ndjson.gz';const UPDATE_URL = 'https://raw.githubusercontent.com/karsl-program/LRJPP/main/main.user.js';const DOWNLOAD_URL = 'https://raw.githubusercontent.com/karsl-program/LRJPP/main/main.user.js';const DIFFICULTY_MAP = {0: '暂未评定',1: '入门',8 行未改动const TYPE_MAP = {'洛谷': 'luogu','主题库': 'P','入门与面试': 'B'};const TYPE_KEYS = Object.keys(TYPE_MAP);const dimensionMaps = {algorithm: ['语言入门','字符串','后缀自动机 SAM','字典树 Trie','AC 自动机','KMP 算法','后缀数组 SA','后缀树','有限状态自动机','回文自动机 PAM','Manacher 算法','顺序结构','分支结构','循环结构','数组','字符串(入门)','结构体','函数与递归','Lyndon 分解','Z 函数','动态规划 DP','搜索','广度优先搜索 BFS','深度优先搜索 DFS','剪枝','记忆化搜索','启发式搜索','迭代加深搜索','启发式迭代加深搜索 IDA*','Dancing Links','爬山算法 Local search','模拟退火','背包 DP','数位 DP','区间 DP','树形 DP','轮廓线 DP','线性 DP','状压 DP','后缀平衡树','数学','图论','Kruskal 重构树','网络流','信息论','随机调整','遗传算法','图论建模','图遍历','拓扑排序','最短路','生成树','平面图','最小环','A* 算法','折半搜索 meet in the middle','梯度下降法','拉格朗日乘数法','拉格朗日插值法','单位根反演','负权环','连通块','2-SAT','平面图欧拉公式','强连通分量','Tarjan','双连通分量','欧拉回路','差分约束','仙人掌','二分图','一般图的最大匹配','上下界网络流','最小割','费用流','圆方树','弦图','Floyd 算法','广义串并联图','Hall 定理','计算几何','树形数据结构','线段树','并查集','平衡树','堆','树状数组','cdq 分治','可并堆','动态树 LCT','三维计算几何','向量','凸包','叉积','线段相交','半平面交','旋转卡壳','极角排序','平面几何','闵可夫斯基和 Minkowski sum','博弈论','线性数据结构','单调队列','颜色段均摊(珂朵莉树 ODT)','树套树','可持久化线段树','可持久化','前缀和','栈','队列','博弈树','整体二分','K-D Tree','Nim 积','李超线段树','吉司机线段树 segment tree beats','线段树合并','SG 函数','二区间合并(猫树分治)','KTT / Kinetic Tournament Tree','原根','多项式','数论','素数判断','最大公约数 gcd','扩展欧几里德算法','不定方程','进制','分块','ST 表','快速傅里叶变换 FFT','快速数论变换 NTT','快速沃尔什变换 FWT','快速莫比乌斯变换 FMT','差分','链表','单调栈','Berlekamp-Massey(BM) 算法','集合幂级数,子集卷积','哈希表','模拟','贪心','基础算法','中国剩余定理 CRT','莫比乌斯反演','逆元','Lucas 定理','类欧几里得算法','调和级数','欧拉降幂','Stern-Brocot 树','整除分块','Dirichlet 卷积','大步小步算法 BSGS','二次剩余','Bézout 定理','杜教筛','欧拉函数','线性筛法','亚线性快速求和算法','递推','倍增','二分','递归','枚举','分治','排序','动态规划优化','优先队列','矩阵加速','斜率优化','状态合并','凸完全单调性(wqs 二分)','四边形不等式','DP 套 DP','动态 DP','决策单调性','STL','整体转移','斜率维护技巧 slope trick','点分治','树上启发式合并','树的遍历','最近公共祖先 LCA','树的直径','树链剖分','树论','群论','置换','Pólya 定理','虚树','组合数学','排列组合','二项式定理','康托展开','基环树','动态树分治','Prüfer 序列','全局平衡二叉树','树的重心','LGV 引理','矩阵树定理','矩阵运算','鸽笼原理','容斥原理','Fibonacci 数列','Catalan 数','Stirling 数','生成函数','概率论','期望','线性代数','矩阵乘法','线性递推','高斯消元','Dilworth 定理','拉格朗日反演','杨表','随机游走 Markov Chain','鞅的停时定理','暴力数据结构','高精度','莫队','三分','离散化','霍夫曼树','哈希 hashing','线性基','微积分','导数','积分','定积分','级数','扫描线','其它技巧','随机化','位运算','构造','行列式','特征值','分数规划','线性规划','双指针 two-pointer','Ad-hoc','笛卡尔树','拟阵','根号分治','模拟费用流','分散层叠','均摊分析','分类讨论','近似算法','线段树分治','离线处理','bitset','组合优化','整数规划','原始对偶','启发式合并','反悔贪心','最大流最小割定理','保序回归'],source: ['各省省选','集训队互测','福建省历届夏令营','NOI','NOIP 普及组','NOIP 提高组','APIO','NOI 导刊','CTT(清华集训/北大集训)','网络流与线性规划 24 题','CSP-S 提高级','CSP-J 入门级','NOI Online','Ynoi','NOI 系列赛事','经典套题','国际知名赛事','WC','CTSC/CTS','模板题','USACO','POI(波兰)','IOI','CCO(加拿大)','CCC(加拿大)','CEOI(中欧)','eJOI(欧洲)','COCI(克罗地亚)','BalticOI(波罗的海)','JOI(日本)','AGM','PA(波兰)','ROI(俄罗斯)','EGOI(欧洲/女生)','NOISG(新加坡)','NordicOI(北欧)','BalkanOI(巴尔干半岛)','KOI(韩国)','RMI(罗马尼亚)','COI(克罗地亚)','洛谷原创','ICPC','洛谷月赛','语言月赛','洛谷比赛','大学竞赛','ROIR(俄罗斯)','INOI(伊朗)','UOI(乌克兰)','JOISC/JOIST(日本)','COTS(克罗地亚)','Google Code Jam','Moscow Olympiad','PO(瑞典)','PAIO','MCC/MCO(马来西亚)','KTSC(韩国)','IATI(保加利亚/东欧)','Google Kick Start','入门赛','蓝桥杯国赛','蓝桥杯省赛','省赛/邀请赛','传智杯','THUPC','GESP','其他竞赛','THUSC','高校校赛','THUWC','CSP-X 小学组','Code+','梦熊比赛','信息与未来','科创活动','BCSP-X','小学活动','初中活动','CSPro','CCPC','科大国创杯','蓝桥杯青少年组'],time: ['1996','1997','1998','1999','2000','2001','2002','2003','2004','2005','2006','2007','2008','2009','2010','2011','2012','2013','2014','2015','2016','2017','2018','2019','2020','2021','2022','2023','2024','2025','2026','2027','2028','2029','2077','2078','2079'],region: ['重庆','四川','河南','浙江','上海','福建','江苏','安徽','湖南','北京','河北','广东','山东','吉林','山西','江西','贵州','广西','陕西','国内省市','辽宁','云南','天津','湖北','黑龙江','海南','甘肃','青海','台湾','内蒙古','西藏','宁夏','新疆','香港','澳门','济南','南京','青岛','国内赛站','EC Final','国际赛区','NERC/NEERC','SEERC','CERC','NWRRC','WF','NAC','杭州','昆明','西安','哈尔滨','首尔','横浜','SWERC','成都','雅加达'],special: ['交互题','提交答案','Special Judge','O2优化','通信题']};const DIMENSION_NAMES = {algorithm: '算法',21 行未改动let acceptedSet = new Set();let submittedSet = new Set();let userStatusReady = false;function compareVersions(v1, v2) {const parts1 = v1.split('.').map(Number);const parts2 = v2.split('.').map(Number);const len = Math.max(parts1.length, parts2.length);for (let i = 0; i < len; i++) {const a = parts1[i] || 0;const b = parts2[i] || 0;if (a > b) return 1;if (a < b) return -1;}return 0;}function checkForUpdate() {return new Promise((resolve) => {console.log('[更新检查] 开始请求', UPDATE_URL);GM_xmlhttpRequest({method: 'GET',url: UPDATE_URL,onload: function(res) {console.log('[更新检查] 响应状态:', res.status);console.log('[更新检查] 响应长度:', res.responseText ? res.responseText.length : 0);try {const text = res.responseText;const versionMatch = text.match(/@version\s+([\d.]+)/);if (!versionMatch) {console.warn('[更新检查] 未解析到版本号');resolve(false);return;}const remoteVersion = versionMatch[1];const currentVersion = GM_info.script.version;console.log('[更新检查] 当前版本:', currentVersion, '远程版本:', remoteVersion);if (compareVersions(remoteVersion, currentVersion) > 0) {console.log('[更新检查] 发现新版本,弹出对话框');showUpdateDialog(currentVersion, remoteVersion);resolve(true);} else {console.log('[更新检查] 已是最新版本');resolve(false);}} catch (e) {console.error('[更新检查] 解析出错', e);resolve(false);}},onerror: function(err) {console.warn('[更新检查] 请求失败', err);resolve(false);}});});}function showUpdateDialog(currentVersion, newVersion) {const existing = document.getElementById('luogu-update-dialog-overlay');if (existing) existing.remove();const overlay = document.createElement('div');overlay.id = 'luogu-update-dialog-overlay';overlay.style.cssText = `position: fixed;top: 0;left: 0;width: 100%;height: 100%;background: rgba(0, 0, 0, 0.4);backdrop-filter: blur(2px);z-index: 2147483647;display: flex;align-items: center;justify-content: center;animation: fadeIn 0.2s ease;`;const dialog = document.createElement('div');dialog.style.cssText = `background: #fff;border-radius: 16px;box-shadow: 0 10px 30px rgba(0,0,0,0.15);padding: 24px 28px;width: 360px;max-width: 90vw;text-align: center;animation: slideUp 0.25s ease;`;const icon = document.createElement('div');icon.innerHTML = '🚀';icon.style.cssText = 'font-size: 42px; margin-bottom: 12px;';const title = document.createElement('h3');title.textContent = '发现新版本';title.style.cssText = 'margin: 0 0 12px; font-size: 20px; font-weight: 700; color: #1a1a1a;';const info = document.createElement('p');info.style.cssText = 'margin: 0 0 24px; font-size: 14px; color: #555; line-height: 1.5;';info.innerHTML = `当前版本 <b>v${currentVersion}</b><br>最新版本 <b style="color: #4f8ef7;">v${newVersion}</b>`;const btnContainer = document.createElement('div');btnContainer.style.cssText = 'display: flex; gap: 12px; justify-content: center;';const laterBtn = document.createElement('button');laterBtn.textContent = '稍后再说';laterBtn.style.cssText = `padding: 8px 20px;font-size: 14px;border: 1px solid #ddd;border-radius: 8px;background: #f5f5f5;cursor: pointer;transition: background 0.2s;`;laterBtn.onmouseenter = () => { laterBtn.style.background = '#e8e8e8'; };laterBtn.onmouseleave = () => { laterBtn.style.background = '#f5f5f5'; };laterBtn.onclick = () => overlay.remove();const updateBtn = document.createElement('button');updateBtn.textContent = '立即更新';updateBtn.style.cssText = `padding: 8px 20px;font-size: 14px;border: none;border-radius: 8px;background: #4f8ef7;color: white;cursor: pointer;transition: background 0.2s;`;updateBtn.onmouseenter = () => { updateBtn.style.background = '#3a7bd5'; };updateBtn.onmouseleave = () => { updateBtn.style.background = '#4f8ef7'; };updateBtn.onclick = () => {window.open(DOWNLOAD_URL, '_blank');overlay.remove();};btnContainer.appendChild(laterBtn);btnContainer.appendChild(updateBtn);dialog.appendChild(icon);dialog.appendChild(title);dialog.appendChild(info);dialog.appendChild(btnContainer);overlay.appendChild(dialog);document.body.appendChild(overlay);const style = document.createElement('style');style.textContent = `@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }@keyframes slideUp { from { transform: translateY(20px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }`;document.head.appendChild(style);}function loadSettings() {try {const raw = localStorage.getItem(STORAGE_KEY);if (!raw) return;const data = JSON.parse(raw);if (data.types) {const validTypes = Object.values(TYPE_MAP);selectedTypes = new Set(Array.from(data.types).filter(v => validTypes.includes(v)));}if (data.difficulties) selectedDifficulties = new Set(data.difficulties);if (data.tags) {DIMENSION_KEYS.forEach(key => {if (data.tags[key] && Array.isArray(data.tags[key])) {279 行未改动全部展开}if (filters.tags) {const tagNames = [];DIMENSION_KEYS.forEach(key => {const tags = filters.tags[key] || new Set();tags.forEach(tag => tagNames.push(tag));});if (tagNames.length > 0) {results = results.filter(p => {if (!p.tags || p.tags.length === 0) return false;return tagNames.every(tag => p.tags.includes(tag));});}}23 行未改动function createFloatingPanel(button) {const panel = document.createElement('div');panel.style.cssText = `position: fixed;background: #fff;border-radius: 12px;box-shadow: 0 8px 24px rgba(0,0,0,0.08);padding: 16px 18px;width: 300px;max-height: 480px;overflow-y: auto;border: 1px solid #eee;z-index: 2147483647;display: none;font-size: 13px;line-height: 1.5;color: #333;190 行未改动全部展开panel.appendChild(actionContainer);DIMENSION_KEYS.forEach(dimKey => {const dimName = DIMENSION_NAMES[dimKey] || dimKey;const tagsList = dimensionMaps[dimKey] || [];const tagSet = selectedTags[dimKey];const section = document.createElement('div');section.style.cssText = 'margin-bottom:14px;';13 行未改动selectedContainer.style.display = 'none';return;}selectedContainer.style.display = 'flex';tagSet.forEach(tagName => {const tagEl = document.createElement('span');tagEl.style.cssText = `display:inline-flex; align-items:center;background:#eef3ff; color:#2b5cd9;padding:2px 10px; border-radius:14px;font-size:11px; gap:4px;`;const nameSpan = document.createElement('span');nameSpan.textContent = tagName;const removeBtn = document.createElement('span');removeBtn.textContent = '×';removeBtn.style.cssText = 'cursor:pointer; font-weight:700; color:#7a8bb0; font-size:14px;';removeBtn.onclick = (e) => {e.stopPropagation();tagSet.delete(tagName);updateSelectedDisplay();saveSettings();};tagEl.appendChild(nameSpan);34 行未改动input.addEventListener('input', function() {const query = this.value.trim().toLowerCase();if (!query) { suggestionBox.style.display = 'none'; return; }const matches = [];for (const tagName of tagsList) {if (tagName.toLowerCase().includes(query)) {if (!matches.includes(tagName)) {matches.push(tagName);}}}if (matches.length === 0) { suggestionBox.style.display = 'none'; return; }suggestionBox.innerHTML = '';matches.slice(0, 10).forEach(tagName => {const item = document.createElement('div');item.style.cssText = `padding:3px 10px; cursor:pointer; font-size:12px;border-bottom:1px solid #f5f5f5;transition:background 0.1s;`;item.onmouseenter = () => { item.style.background = '#f5f7fa'; };item.onmouseleave = () => { item.style.background = 'transparent'; };item.addEventListener('mousedown', function(e) { e.preventDefault(); });item.onclick = () => {if (!tagSet.has(tagName)) {tagSet.add(tagName);updateSelectedDisplay();saveSettings();}input.value = '';suggestionBox.style.display = 'none';};const nameSpan = document.createElement('span');nameSpan.textContent = tagName;item.appendChild(nameSpan);suggestionBox.appendChild(item);});suggestionBox.style.display = 'block';});26 行未改动let hoverTimeout = null;button.addEventListener('mouseenter', function() {clearTimeout(hoverTimeout);panel.style.display = 'block';const rect = button.getBoundingClientRect();const panelRect = panel.getBoundingClientRect();let left = rect.right - panelRect.width;if (left < 10) left = 10;const maxLeft = window.innerWidth - panelRect.width - 10;if (left > maxLeft) left = maxLeft;let top = rect.top - panelRect.height - 10;if (top < 10) {top = rect.bottom + 10;}panel.style.left = left + 'px';panel.style.top = top + 'px';panel.style.bottom = 'auto';panel.style.right = 'auto';});button.addEventListener('mouseleave', function(e) {hoverTimeout = setTimeout(() => {142 行未改动全部展开difficulty: obj.difficulty,type: obj.type,tags: obj.tags || []});} catch (e) {}}if (batch.length === 0) {if (end < total) importBatch(end);else resolve();40 行未改动async function initCore() {setupUI();console.log('【洛谷随机跳题】UI 已创建,等待用户状态初始化...');checkForUpdate().catch(err => console.warn('检查更新失败', err));waitForUid().then(async (uid) => {if (uid) {const success = await initUserStatus(uid);if (success) {62 行未改动}})();```:::将**难度文字**改为入门:::info[]```// ==UserScript==// @name 洛谷难度强制改入门(全页面通用版)// @namespace http://tampermonkey.net/// @version 15.0// @description 适配题目详情、列表、题单、用户练习情况页。清洗特殊符号,精准替换难度为“入门”,保留颜色// @match *://*.luogu.com.cn/*// @match *://*.luogu.com/*// @run-at document-end// @grant none// ==/UserScript==(function() {'use strict';console.log('【油猴脚本】v15.0 全页面通用版启动!');const difficultyTexts = ['入门', '普及-', '普及', '普及+/提高-', '普及/提高-','提高', '提高+/省选-', '省选/NOI-', 'NOI/NOI+/CTS', 'NOI/NOI+/CTSC','暂无评定'];function cleanText(str) {return str.replace(/[\s\u00a0\u200b]+/g, '').replace(/[−—–]/g, '-');}const cleanDifficultyTexts = difficultyTexts.map(cleanText);function replaceDifficulty() {const walker = document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT,null,false);let node;let changedCount = 0;while (node = walker.nextNode()) {const text = cleanText(node.nodeValue);if (cleanDifficultyTexts.includes(text) && text !== '入门') {node.nodeValue = '入门';changedCount++;}}if (changedCount > 0) {console.log(`【油猴脚本】成功将 ${changedCount} 处难度替换为“入门”!`);}}setInterval(replaceDifficulty, 100);const observer = new MutationObserver(() => {replaceDifficulty();});function init() {if (document.body) {observer.observe(document.body, {childList: true,subtree: true});replaceDifficulty();} else {setTimeout(init, 50);}}init();})();```:::虚假 **RMJ**( https://www.luogu.com.cn/discuss/1399108 https://www.luogu.com.cn/discuss/1409952 ):::info```// ==UserScript==// @name GenGen-RMJ// @icon https://cdn.luogu.com.cn/upload/image_hosting/yy27itbl.png// @namespace https://gengen.qzz.io/// @version 5.3// @description GenGen RMJ// @author GenGen Dev// @run-at document-start// @match https://challenges.cloudflare.com/cdn-cgi/challenge-platform/*// @match https://www.luogu.com.cn/*// @match https://atcoder.jp/contests/*/submit?RMJ=1// @match https://atcoder.jp/contests/*/submissions/me// @match https://codeforces.com/*// @connect *// @inject-into page// @grant GM_addStyle// @grant GM_xmlhttpRequest// @grant GM_setValue// @grant GM_getValue// @grant unsafeWindow// @license MIT// ==/UserScript==// 重定向遮罩(() => {const h = location.href;if (h.includes('challenges.cloudflare.com')) return;let flag = '';try { flag = GM_getValue('rmj-flag-action', ''); } catch { /* ignore */ }const ref = document.referrer || '';if (!(ref.includes('RMJ=1') || flag === 'submit')) return;const isStatus =h.includes('codeforces.com/problemset/status') ||(h.includes('atcoder.jp/contests/') && h.includes('/submissions/me'));if (!isStatus) return;const m = document.createElement('div');m.id = 'rmj-redirect-mask';m.style.cssText = 'position:fixed;inset:0;z-index:2147483647;background:#efefef;';const attach = () => {if (!document.getElementById('rmj-redirect-mask')) {(document.documentElement || document.body).appendChild(m);}};if (document.documentElement) attach();else new MutationObserver((_, o) => {if (document.documentElement) { o.disconnect(); attach(); }}).observe(document, { childList: true });})();(() => {'use strict';const TAG = '[RMJ]';const LOG = (...a) => console.log(TAG, ...a);const ERR = (...a) => console.error(TAG, ...a);const HOST = location.hostname;const isLuogu = () => HOST === 'www.luogu.com.cn';const isCF = () => HOST === 'codeforces.com';const isAT = () => HOST === 'atcoder.jp';const isCfChallenge = () => HOST === 'challenges.cloudflare.com';const docReady = (fn) =>document.readyState === 'loading'? document.addEventListener('DOMContentLoaded', fn, { once: true }): fn();const sleep = (ms) => new Promise((r) => setTimeout(r, ms));const waitFor = (selector, cb, timeout = 12000) => {const t0 = Date.now();const timer = setInterval(() => {const el = document.querySelector(selector);if (el) {clearInterval(timer);cb(el);} else if (Date.now() - t0 > timeout) {clearInterval(timer);}}, 120);return timer;};const waitForEl = (selector, timeout = 10000) =>new Promise((resolve, reject) => {const hit = document.querySelector(selector);if (hit) return resolve(hit);const root = document.body || document.documentElement;const obs = new MutationObserver(() => {const el = document.querySelector(selector);if (el) {obs.disconnect();clearTimeout(timer);resolve(el);}});obs.observe(root, { childList: true, subtree: true });const timer = setTimeout(() => {obs.disconnect();reject(new Error('超时: ' + selector));}, timeout);});const Timers = () => {const set = new Set();return {iv(fn, ms) { const id = setInterval(fn, ms); set.add(id); return id; },to(fn, ms) { const id = setTimeout(() => { set.delete(id); fn(); }, ms); set.add(id); return id; },clear(id) { set.delete(id); clearInterval(id); clearTimeout(id); },clearAll() { for (const id of set) { clearInterval(id); clearTimeout(id); } set.clear(); }};};// 主题存储const ThemeStore = (() => {const P = 'gen-at-';const get = (k) => GM_getValue(P + k, '');const set = (k, v) => GM_setValue(P + k, String(v));// 从洛谷 .theme-page 提取,找不到容器则不写入const extractFromLuogu = () => {const el =document.querySelector('.theme-page.theme-frosted') ||document.querySelector('.theme-page') ||document.querySelector('[class*="theme-page"]');if (!el) return false;const inlineStyle = (el.getAttribute('style') || '').replace(/"/g, '"');let computed = null;try { computed = getComputedStyle(el); } catch { computed = null; }const readVar = (name) => {if (inlineStyle) {const re = new RegExp(name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\s*:\\s*([^;]+)');const m = inlineStyle.match(re);if (m && m[1].trim()) return m[1].trim();}if (computed) {const v = computed.getPropertyValue(name);if (v && v.trim()) return v.trim();}return '';};const vars = {body_back: '--theme-body-back',bg_image: '--theme-body-image',bg_color: '--theme-body-color',bg_repeat: '--theme-body-image-repeat',bg_size: '--theme-body-image-size',bg_pos: '--theme-body-image-position',mid_mask: '--theme-body-mid-mask',color_filter: '--theme-body-color-filter',card_bg: '--theme-card-background',card_blur: '--theme-card-backdrop-filter',};let found = false;for (const [key, cssVar] of Object.entries(vars)) {const v = readVar(cssVar);if (v) { set(key, v); found = true; }}try {const nu = document.querySelector('#app .user-nav .title span');if (nu && nu.textContent.trim()) set('luogu_user', nu.textContent.trim());const av = document.querySelector('#app .top-bar .avatar img');if (av && av.src) set('luogu_avatar', av.src);} catch { /* ignore */ }return found;};const extractWithRetry = (maxAttempts = 25, interval = 200) => {let n = 0;const tryIt = () => {if (extractFromLuogu()) return;if (++n < maxAttempts) setTimeout(tryIt, interval);};tryIt();};// 应用到任意遮罩容器const applyTo = (el) => {if (!el) return;const b64 = get('bg_b64');const raw = get('bg_image');let img = '';if (b64) {img = `url(${b64})`;} else if (raw) {const m = raw.match(/url\(\s*(['"]?)(.+?)\1\s*\)/i);let u = m ? m[2] : raw;if (u && !/^https?:\/\//i.test(u) && !/^data:/i.test(u)) {try { u = new URL(u, 'https://www.luogu.com.cn/').href; } catch { /* keep */ }}if (u && u !== 'none') img = /^url\(/i.test(raw) ? `url(${u})` : `url(${u})`;}const M = {'--rmj-back': get('body_back') || '#f5f5f5','--rmj-img': img,'--rmj-color': get('bg_color'),'--rmj-repeat': get('bg_repeat') || 'no-repeat','--rmj-size': get('bg_size') || 'cover','--rmj-pos': get('bg_pos') || 'center','--rmj-mask': get('mid_mask') || 'none','--rmj-filter': get('color_filter') || 'none','--rmj-card': get('card_bg') || 'rgba(255,255,255,.78)','--rmj-blur': get('card_blur') || 'blur(14px)',};for (const [k, v] of Object.entries(M)) {if (v) el.style.setProperty(k, v);}};return { get, set, applyTo, extractFromLuogu, extractWithRetry };})();// 共享遮罩样式GM_addStyle(`.rmj-ovl-base{position:fixed!important;inset:0!important;z-index:2147483647!important;display:flex!important;align-items:center!important;justify-content:center!important;overflow:hidden!important;pointer-events:all!important;cursor:default!important;background:var(--rmj-back,#f5f5f5)!important;color:#333!important;box-sizing:border-box!important;-webkit-font-smoothing:antialiased!important;}.rmj-ovl-base *{box-sizing:border-box!important;margin:0!important;padding:0!important;font-family:inherit!important;line-height:inherit!important}.rmj-ovl-base .rmj-ly{position:absolute!important;inset:0!important;pointer-events:none!important;-webkit-mask:var(--rmj-mask,none) no-repeat/100% 100%!important;mask:var(--rmj-mask,none) no-repeat/100% 100%!important}.rmj-ovl-base .rmj-ly-c{background:var(--rmj-color,transparent)!important;filter:var(--rmj-filter,none)!important}.rmj-ovl-base .rmj-ly-i{background:var(--rmj-img,none) var(--rmj-pos,center)/var(--rmj-size,cover) var(--rmj-repeat,no-repeat)!important}.rmj-ovl-card{position:relative!important;z-index:1!important;width:420px!important;max-width:90vw!important;padding:36px 32px 40px!important;border-radius:4px!important;border:none!important;background:var(--rmj-card,rgba(255,255,255,.78))!important;backdrop-filter:var(--rmj-blur,blur(14px))!important;-webkit-backdrop-filter:var(--rmj-blur,blur(14px))!important;box-shadow:0 8px 32px rgba(0,0,0,.18),0 1.5px 6px rgba(0,0,0,.08)!important;display:flex!important;flex-direction:column!important;align-items:center!important;gap:20px!important;}.rmj-ovl-card h2{font-size:20px!important;font-weight:600!important;color:#333!important;letter-spacing:.5px!important;user-select:none!important;text-align:center!important}.rmj-ovl-card p{font-size:13px!important;color:#888!important;text-align:center!important;user-select:none!important}.rmj-ovl-spin{width:26px;height:26px;border:3px solid rgba(0,0,0,.1);border-top-color:#005c97;border-radius:50%;animation:rmj-ovl-spin .7s linear infinite}@keyframes rmj-ovl-spin{to{transform:rotate(360deg)}}`);// 路由const Router = (() => {const handlers = new Set();let last = location.href;const notify = () => {const cur = location.href;if (cur === last) return;last = cur;for (const fn of handlers) {try { fn(cur); } catch (e) { ERR('路由回调异常', e); }}};const wrap = (name) => {const orig = history[name];if (!orig || orig.__rmjWrapped) return;const wrapped = function (...args) {const ret = orig.apply(this, args);setTimeout(notify, 0);return ret;};wrapped.__rmjWrapped = true;history[name] = wrapped;};wrap('pushState');wrap('replaceState');addEventListener('popstate', notify, true);addEventListener('hashchange', notify, true);return {on(fn) { handlers.add(fn); return () => handlers.delete(fn); },notify,};})();const CACHE_CF = 'cf-submissions-cache';const CACHE_AT = 'at-submissions-cache';const LAST_UPDATE_CF = 'cf-last-update';const LAST_UPDATE_AT = 'at-last-update';const SYNC_INTERVAL_MS = 24 * 60 * 60 * 1000;const FINAL_AT = new Set(['AC', 'WA', 'CE', 'RE', 'TLE', 'MLE', 'OLE', 'IE']);// CF 挑战页补丁const CfChallengePatch = {applied: false,apply() {if (this.applied || !isCfChallenge()) return;this.applied = true;const XHR = (unsafeWindow || window).XMLHttpRequest;if (!XHR) return;const origOpen = XHR.prototype.open;const origSend = XHR.prototype.send;XHR.prototype.open = function (method, url) {this._rmjUrl = url || '';return origOpen.apply(this, arguments);};XHR.prototype.send = function (body) {if (this._rmjUrl) this.timeout = undefined;return origSend.apply(this, arguments);};}};// 洛谷主界面const MainUI = (() => {const VERSION = '5.3';const POLL_MS = 1000;const SVG = {ok: `<svg class="svg-inline--fa fa-check lcolor--success" data-prefix="fas" data-icon="check" role="img" viewBox="0 0 448 512" aria-hidden="true"><path class="" fill="currentColor" d="M434.8 70.1c14.3 10.4 17.5 30.4 7.1 44.7l-256 352c-5.5 7.6-14 12.3-23.4 13.1s-18.5-2.7-25.1-9.3l-128-128c-12.5-12.5-12.5-32.8 0-45.3s32.8-12.5 45.3 0l101.5 101.5 234-321.7c10.4-14.3 30.4-17.5 44.7-7.1z"></path></svg>`,err: `<svg class="svg-inline--fa fa-xmark lcolor--error" data-prefix="fas" data-icon="xmark" role="img" viewBox="0 0 384 512" aria-hidden="true"><path class="" fill="currentColor" d="M55.1 73.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3L147.2 256 9.9 393.4c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0L192.5 301.3 329.9 438.6c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L237.8 256 375.1 118.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L192.5 210.7 55.1 73.4z"></path></svg>`,na: `<svg class="svg-inline--fa fa-minus lcolor--grey-4" data-prefix="fas" data-icon="minus" role="img" viewBox="0 0 448 512" aria-hidden="true"><path class="" fill="currentColor" d="M0 256c0-17.7 14.3-32 32-32l384 0c17.7 0 32 14.3 32 32s-14.3 32-32 32L32 288c-17.7 0-32-14.3-32-32z"></path></svg>`};const C = {ac: '#52c41a', wa: '#e74c3c', na: '#404040',p: '#0ea5e9', bd: '#e2e8f0', t: '#1e293b',m: '#64748b', bg: '#fff', alt: '#f8fafc'};GM_addStyle(`.rmj-trigger{display:inline-flex;align-items:center;gap:8px;padding:8px 16px;background:#fff;color:${C.t};border:1px solid ${C.bd};border-radius:8px;font-weight:600;font-size:13px;cursor:pointer;transition:border-color .18s ease,color .18s ease,box-shadow .18s ease;box-shadow:0 1px 3px rgba(0,0,0,.04);user-select:none;margin-right:10px;height:36px}.rmj-trigger:hover{border-color:${C.p};color:${C.p};box-shadow:0 2px 10px rgba(14,165,233,.14)}.rmj-trigger:active{box-shadow:0 1px 3px rgba(14,165,233,.18) inset}.rmj-trigger img{width:20px;height:20px;border-radius:4px}.rmj-overlay{pointer-events:none;position:fixed;inset:0;background:rgba(0,0,0,.4);z-index:2147483646;display:flex;align-items:center;justify-content:center;opacity:0;visibility:hidden;transition:opacity .22s ease,visibility .22s ease}.rmj-overlay.show{opacity:1;visibility:visible;pointer-events:auto}.rmj-modal{width:480px;max-height:85vh;background:rgba(255,255,255,0.82);backdrop-filter:blur(10px);border-radius:12px;box-shadow:0 25px 60px rgba(0,0,0,.14);display:flex;flex-direction:column;overflow:hidden;transform:scale(.97);transition:transform .25s cubic-bezier(.25,.8,.32,1),height .25s ease}.rmj-overlay.show .rmj-modal{transform:scale(1)}.rmj-overlay:not(.show) .rmj-modal *{pointer-events:none!important;cursor:default!important}.rmj-overlay:not(.show) .rmj-modal a{color:inherit!important;text-decoration:none!important}.rmj-pages{flex:1;overflow:hidden;position:relative;min-height:0;height:auto;transition:height .28s ease}.rmj-page:not(.active){visibility:hidden;pointer-events:none;position:absolute;top:0;left:50%;width:50%;height:100%}.rmj-page.active{visibility:visible;pointer-events:auto;opacity:1;z-index:1}.rmj-head{padding:20px 24px 16px;border-bottom:1px solid ${C.bd};display:flex;align-items:center;gap:12px}.rmj-head img{width:36px;height:36px;border-radius:8px}.rmj-title{flex:1;margin:0;font-weight:700;font-size:20px;background:linear-gradient(135deg,${C.p},#2563eb);-webkit-background-clip:text;-webkit-text-fill-color:transparent}.rmj-close{width:32px;height:32px;border:0;background:0 0;color:${C.m};cursor:pointer;border-radius:6px;display:flex;align-items:center;justify-content:center;font-size:20px;transition:background .15s ease,color .15s ease}.rmj-close:hover{background:${C.alt};color:${C.t}}.rmj-pages{display:grid;width:100%;overflow:hidden;transition:height .28s ease}.rmj-pages-inner{display:contents}.rmj-page{grid-area:1/1/2/2;padding:24px;overflow-y:auto;box-sizing:border-box;visibility:hidden;pointer-events:none;opacity:0;transition:opacity .25s ease,visibility .25s}.rmj-welcome-title{font-size:18px;font-weight:700;color:${C.t};margin-bottom:12px}.rmj-update-badge{display:inline-block;padding:3px 10px;background:linear-gradient(135deg,${C.p},#2563eb);color:#fff;border-radius:20px;font-size:11px;font-weight:600;margin-left:8px}.rmj-feat{list-style:none;padding:0;margin:16px 0}.rmj-feat li{display:flex;align-items:flex-start;gap:10px;padding:8px 0;color:${C.m};font-size:14px;line-height:1.5}.rmj-feat li::before{content:'·';flex-shrink:0}.rmj-sec{font-size:11px;font-weight:700;color:${C.m};text-transform:uppercase;letter-spacing:1px;margin:0 0 12px}.rmj-sec:not(:first-child){margin-top:20px}.rmj-card{background:${C.alt};border:1px solid ${C.bd};border-radius:10px;padding:14px 16px;display:flex;align-items:center;justify-content:space-between;transition:border-color .18s ease,box-shadow .18s ease,background .18s ease}.rmj-card:hover{border-color:rgba(14,165,233,.35);box-shadow:0 2px 10px rgba(14,165,233,.08);background:#fff}.rmj-card+.rmj-card{margin-top:8px}.rmj-info{display:flex;align-items:center;gap:12px}.rmj-logo{width:32px;height:32px;border-radius:6px;object-fit:contain}.rmj-name{font-size:14px;font-weight:600;color:${C.t}}.rmj-badge{display:inline-flex;align-items:center;gap:4px;padding:4px 12px;border-radius:20px;font-size:12px;font-weight:600}.rmj-badge.on{background:rgba(82,196,26,.09);color:${C.ac}}.rmj-badge.off{background:rgba(231,76,60,.09);color:${C.wa};cursor:pointer;text-decoration:none;transition:background .15s ease,color .15s ease}.rmj-badge.off:hover{background:rgba(231,76,60,.16)}.rmj-badge.load{background:#f1f5f9;color:${C.m}}.rmj-spin{width:14px;height:14px;border:2px solid ${C.bd};border-top-color:${C.p};border-radius:50%;animation:spin .8s linear infinite}@keyframes spin{to{transform:rotate(360deg)}}.rmj-links{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-top:12px}.rmj-link{display:flex;align-items:center;gap:8px;padding:10px 12px;background:${C.alt};border:1px solid ${C.bd};border-radius:8px;color:${C.t};text-decoration:none;font-size:13px;font-weight:500;transition:border-color .18s ease,color .18s ease,box-shadow .18s ease,background .18s ease}.rmj-link:hover{border-color:${C.p};color:${C.p};background:#fff;box-shadow:0 2px 10px rgba(14,165,233,.10)}.rmj-link svg{width:16px;height:16px;flex-shrink:0}.rmj-foot{padding:16px 24px;border-top:1px solid ${C.bd};display:flex;align-items:center;justify-content:space-between;background:${C.alt}}.rmj-btn{padding:8px 16px;border:1px solid ${C.bd};background:#fff;color:${C.t};border-radius:6px;font-size:13px;font-weight:500;cursor:pointer;transition:border-color .15s ease,color .15s ease,background .15s ease}.rmj-btn:hover:not(:disabled){border-color:${C.p};color:${C.p};background:#f8fafc}.rmj-btn:disabled{opacity:.4;cursor:not-allowed}.rmj-dots{display:flex;gap:6px}.rmj-dot{width:6px;height:6px;border-radius:50%;background:${C.bd};transition:background .2s ease,width .2s ease}.rmj-dot.active{background:${C.p};width:18px;border-radius:3px}.rmj-prob{display:inline-flex;align-items:center;transition:color .3s ease}.rmj-prob.ac{color:${C.ac};font-weight:bold}.rmj-prob.wa{color:${C.wa};font-weight:bold}.rmj-prob.na{color:#3498db}.rmj-ico{position:absolute;inset:0;background:0 0;display:flex;align-items:center;justify-content:center;z-index:10;border-radius:inherit;animation:fadeIn .3s}.rmj-ico svg{width:18px;height:18px;animation:popIn .3s cubic-bezier(.34,1.56,.64,1)}.rmj-hide>*:not(.rmj-ico){visibility:hidden!important}@keyframes fadeIn{from{opacity:0}to{opacity:1}}@keyframes popIn{from{transform:scale(.5);opacity:0}to{transform:scale(1);opacity:1}}@keyframes badgePop{0%{transform:scale(.8);opacity:0}60%{transform:scale(1.05)}100%{transform:scale(1);opacity:1}}.rmj-record-badge{animation:badgePop .4s ease-out}.rmj-sel{position:relative;display:inline-block;margin-left:8px}.rmj-sel-btn{position:relative;display:inline-flex;align-items:center;min-width:120px;padding:.3125em 1.5em .3125em 1em;border:1px solid #ccc;border-radius:3px;background:#fff;font-size:14px;line-height:1.4;cursor:pointer;text-align:left}.rmj-sel-btn::after{content:"";position:absolute;right:10px;top:50%;width:6px;height:6px;border-right:1.5px solid #555;border-bottom:1.5px solid #555;transform:translateY(-65%) rotate(45deg);transition:transform .2s}.rmj-sel.open .rmj-sel-btn::after{transform:translateY(-35%) rotate(-135deg)}.rmj-sel-menu{position:absolute;top:calc(100% + 4px);left:0;width:100%;margin:0;padding:4px 0;list-style:none;background:#fff;border:1px solid #ccc;border-radius:4px;box-shadow:0 4px 12px rgba(0,0,0,.1);opacity:0;transform:translateY(-8px);pointer-events:none;transition:opacity .2s ease,transform .2s ease;z-index:100}.rmj-sel-menu.open{opacity:1;transform:translateY(0);pointer-events:all}.rmj-sel-menu li{padding:3px 12px;cursor:pointer;font-size:14px}.rmj-sel-menu li:hover{background:#f0f9ff}.rmj-refresh-wrap{display:inline-flex;align-items:center;margin-left:8px;cursor:pointer;color:${C.m};transition:color .18s ease,transform .25s ease}.rmj-refresh-wrap:hover{color:${C.p};transform:rotate(90deg)}.rmj-refresh{width:14px;height:14px}.rmj-switch{position:relative;display:inline-block;width:40px;height:22px}.rmj-switch input{opacity:0;width:0;height:0}.rmj-slider{position:absolute;cursor:pointer;inset:0;background:#ccc;transition:background .2s ease;border-radius:22px}.rmj-slider:before{position:absolute;content:"";height:16px;width:16px;left:3px;bottom:3px;background:#fff;transition:transform .2s ease;border-radius:50%}.rmj-switch input:checked + .rmj-slider{background:${C.p}}.rmj-switch input:checked + .rmj-slider:before{transform:translateX(18px)}.rmj-switch input:disabled + .rmj-slider{opacity:.5;cursor:not-allowed}`);const cfMap = new Map();const atMap = new Map();let cfRawCache = '';let atRawCache = '';let atCapturing = false;let listTimer = null;let problemTimer = null;let problemObserver = null;let problemGen = 0;let currentProblemPath = '';let modalEl = null;let modalPage = 0;let cfPollTimer = null;let atLoginPollTimer = null;const SPECIAL_ACCOUNTS = ['General0000000826', 'General000000826'];const isSpecialAccount = () => {const cfH = GM_getValue('cf-handle', '');const atH = GM_getValue('at-handle', '');return SPECIAL_ACCOUNTS.includes(cfH) || SPECIAL_ACCOUNTS.includes(atH);};const isSyncDisabled = () => {if (isSpecialAccount()) return true;let fromParams = false;try {const params = new URLSearchParams(location.search);fromParams = params.get('rmj-disable-sync') === 'true';} catch (e) { /* ignore */ }if (fromParams) return true;if (GM_getValue('rmj-disable-sync', null) === null) {GM_setValue('rmj-disable-sync', false);}return GM_getValue('rmj-disable-sync', false) === true;};const captureCfHandle = () => {if (!isCF()) return;const attempt = () => {const el = document.querySelector('#header > div.lang-chooser > div:nth-child(2) > a:nth-child(1)');if (!el) return setTimeout(attempt, 1000);const text = el.textContent.trim();if (text && !['Enter', '登录'].includes(text)) {const stored = GM_getValue('cf-handle', '');if (stored !== text) GM_setValue('cf-handle', text);}};attempt();};// 拉取 AT 用户名;未登录返回 nullconst fetchAtHandle = () => new Promise((resolve) => {GM_xmlhttpRequest({method: 'GET',url: 'https://atcoder.jp/',timeout: 8000,onload: (r) => {if (r.status !== 200) return resolve(null);try {const doc = new DOMParser().parseFromString(r.responseText, 'text/html');const el = doc.querySelector('#navbar-collapse > ul.nav.navbar-nav.navbar-right > li:nth-child(2) > a');if (!el) return resolve(null);const t = el.textContent.trim();if (!t || ['Sign Up', 'Login', '登录'].includes(t)) return resolve(null);resolve(t);} catch { resolve(null); }},onerror: () => resolve(null),ontimeout: () => resolve(null),});});const captureAtHandle = async () => {atCapturing = true;updateModal();const handle = await fetchAtHandle();if (handle) {const stored = GM_getValue('at-handle', '');if (stored !== handle) GM_setValue('at-handle', handle);atCapturing = false;return updateModal();}// 未登录:打开登录页并 5s 轮询try { window.open('https://atcoder.jp/login?lang=en', '_blank'); } catch { /* ignore */ }if (atLoginPollTimer) clearInterval(atLoginPollTimer);let polls = 0;atLoginPollTimer = setInterval(async () => {polls++;if (polls > 60) {clearInterval(atLoginPollTimer);atLoginPollTimer = null;atCapturing = false;updateModal();return;}const h = await fetchAtHandle();if (h) {clearInterval(atLoginPollTimer);atLoginPollTimer = null;const stored = GM_getValue('at-handle', '');if (stored !== h) GM_setValue('at-handle', h);atCapturing = false;updateModal();}}, 5000);};const readCaches = () => {try {const cfData = GM_getValue(CACHE_CF, '[]');const atData = GM_getValue(CACHE_AT, '[]');if (cfData !== cfRawCache) {cfRawCache = cfData;cfMap.clear();JSON.parse(cfData).forEach((s) => {const m = s?.taskDisplay?.match(/CF[A-Z0-9]+/i);if (!m) return;const key = m[0].toUpperCase();const status = s.status || null;if (!cfMap.has(key) || (cfMap.get(key) !== 'OK' && status === 'OK')) {cfMap.set(key, status);}});}if (atData !== atRawCache) {atRawCache = atData;atMap.clear();JSON.parse(atData).forEach((s) => {if (!s?.taskKey) return;const key = s.taskKey.toLowerCase();const status = s.status || null;if (!atMap.has(key) || (atMap.get(key) !== 'AC' && status === 'AC')) {atMap.set(key, status);}});}} catch (e) { ERR(e); }};const queryStatus = (pid) => {if (/^CF[A-Z0-9]+$/i.test(pid)) {const v = cfMap.get(pid.toUpperCase());return v === 'OK' ? 'AC' : v ? 'WA' : 'NONE';}if (/^AT_/i.test(pid)) {const k = pid.replace(/^AT_/i, '').toLowerCase();const v = atMap.get(k);return v === 'AC' ? 'AC' : v ? 'WA' : 'NONE';}return null;};const updateListIcons = () => {readCaches();document.querySelectorAll('.row').forEach((row) => {const [sc, pc] = row.children;if (!pc) return;const m = pc.textContent.trim().match(/^(\S+)/);if (!m) return;const st = queryStatus(m[1]);if (!st) {const ov = sc.querySelector('.rmj-ico');if (ov) { ov.remove(); sc.classList.remove('rmj-hide'); }return;}let ov = sc.querySelector('.rmj-ico');if (!ov) {ov = document.createElement('div');ov.className = 'rmj-ico';sc.style.position = 'relative';sc.appendChild(ov);sc.classList.add('rmj-hide');}const icon = st === 'AC' ? SVG.ok : st === 'WA' ? SVG.err : SVG.na;if (ov.dataset.s !== st) { ov.innerHTML = icon; ov.dataset.s = st; }});};const startListPoll = () => {if (listTimer) return;updateListIcons();listTimer = setInterval(updateListIcons, POLL_MS);};const stopListPoll = () => {if (!listTimer) return;clearInterval(listTimer);listTimer = null;};const updateProblemBadge = () => {readCaches();const pid = location.pathname.split('/problem/')[1];if (!pid) return;const st = queryStatus(pid);if (!st) return;const link = document.querySelectorAll('a[href*="/record/list?pid="]')[0];if (!link) return;let tag = link.querySelector('.rmj-prob');if (!tag) {const orig = link.querySelector('span');if (orig) orig.style.display = 'none';tag = document.createElement('span');tag.className = 'rmj-prob';link.appendChild(tag);}const way = document.querySelectorAll('a[href*="https://help.luogu.com.cn/manual/luogu/problem/remote-judge"]')[0];if (way && way.textContent !== 'GenGen RMJ') {way.textContent = 'GenGen RMJ';way.href = 'https://gengen.qzz.io/rmj/';}const cls = st === 'AC' ? 'ac' : st === 'WA' ? 'wa' : 'na';const txt = st === 'AC' ? 'Accepted' : st === 'WA' ? 'Unaccepted' : '暂无';if (tag.dataset.s !== st) {tag.className = 'rmj-prob ' + cls;tag.innerHTML = txt;tag.dataset.s = st;}};const startProblemPoll = () => {if (problemTimer) return;updateProblemBadge();problemTimer = setInterval(updateProblemBadge, POLL_MS);};const stopProblemPoll = () => {if (!problemTimer) return;clearInterval(problemTimer);problemTimer = null;};const teardownProblemObserver = () => {problemGen++;if (problemObserver) { problemObserver.disconnect(); problemObserver = null; }currentProblemPath = '';};const startCfPoll = () => {if (cfPollTimer) clearInterval(cfPollTimer);const initialHandle = GM_getValue('cf-handle', '');let checks = 0;cfPollTimer = setInterval(() => {checks++;const current = GM_getValue('cf-handle', '');if (current !== initialHandle || checks > 60) {clearInterval(cfPollTimer);cfPollTimer = null;updateModal();}}, 1000);updateModal();};const buildModal = () => {if (modalEl) modalEl.remove();modalEl = document.createElement('div');modalEl.className = 'rmj-overlay';modalEl.innerHTML = `<div class="rmj-modal"><div class="rmj-head"><img src="https://cdn.luogu.com.cn/upload/image_hosting/yy27itbl.png"><h2 class="rmj-title">GenGen RMJ</h2><button class="rmj-close">×</button></div><div class="rmj-pages"><div class="rmj-pages-inner"><div class="rmj-page"><div class="rmj-welcome-title">👋 欢迎使用 GenGen RMJ 5 正式版 <span class="rmj-update-badge">v${VERSION}</span></div><p style="color:${C.m};font-size:14px;margin:0 0 8px">在洛谷上无缝刷 Codeforces 和 AtCoder 题目,同步提交记录。</p><ul class="rmj-feat"><strong><li>请点击下一页来绑定你的账户!</li></strong><li>自动同步 CF/AT 账号提交记录</li><li>题目列表和题单直观显示通过状态</li><li>Cloudflare 验证加速绕过</li><li>记录详细查看功能</li><li>最新更新:完全适配新前端</li></ul></div><div class="rmj-page"><div class="rmj-sec">账号绑定</div><div class="rmj-card"><div class="rmj-info"><img class="rmj-logo" src="https://codeforces.com/codeforces.org/s/33478/android-icon-192x192.png"><div class="rmj-name">Codeforces</div></div><div id="rmj-cf"></div></div><div class="rmj-card"><div class="rmj-info"><img class="rmj-logo" src="https://img.atcoder.jp/assets/atcoder.png"><div class="rmj-name">AtCoder</div></div><div id="rmj-at"></div></div><div class="rmj-sec">设置</div><div class="rmj-card"><div class="rmj-info"><div class="rmj-name">自动同步</div></div><label class="rmj-switch"><input type="checkbox" id="rmj-disable-sync"><span class="rmj-slider"></span></label></div><div class="rmj-sec">快捷链接</div><div class="rmj-links"><a class="rmj-link" href="https://gengen.qzz.io" target="_blank"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>官网</a><a class="rmj-link" href="https://gengen.qzz.io/ticket/" target="_blank"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>反馈</a><a class="rmj-link" href="https://scriptcat.org/scripts/code/5099/GenGen-RMJ.user.js" target="_blank"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>源码</a><a class="rmj-link" href="https://www.luogu.me/article/ttethqcb" target="_blank"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg>文章</a></div></div></div></div><div class="rmj-foot"><button class="rmj-btn rmj-prev" disabled>← 上一页</button><div class="rmj-dots"><div class="rmj-dot active"></div><div class="rmj-dot"></div></div><button class="rmj-btn rmj-next">下一页 →</button></div></div>`;document.body.appendChild(modalEl);modalEl.querySelector('.rmj-close').onclick = () => {GM_setValue('rmj-version-shown', VERSION);hideModal();modalEl.addEventListener('click', (e) => {if (!modalEl.classList.contains('show')) {e.stopImmediatePropagation();e.preventDefault();}}, true);};modalEl.querySelector('.rmj-prev').onclick = () => switchModalPage(0);modalEl.querySelector('.rmj-next').onclick = () => switchModalPage(1);updateModal();};const updateModal = () => {if (!modalEl) return;const cfH = GM_getValue('cf-handle', '');const atH = GM_getValue('at-handle', '');const cfEl = modalEl.querySelector('#rmj-cf');const atEl = modalEl.querySelector('#rmj-at');const refreshIcon = `<span class="rmj-refresh-wrap"><svg class="rmj-refresh" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M23 4v6h-6M1 20v-6h6"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg></span>`;if (cfPollTimer) {cfEl.innerHTML = `<span class="rmj-badge load"><span class="rmj-spin"></span>同步中...</span>`;} else if (cfH) {cfEl.innerHTML = `<span class="rmj-badge on">${cfH}</span>${refreshIcon}`;} else {cfEl.innerHTML = `<a class="rmj-badge off" href="https://codeforces.com/enter" target="_blank" id="rmj-cf-bind">去绑定 →</a>`;}if (atCapturing) {atEl.innerHTML = `<span class="rmj-badge load"><span class="rmj-spin"></span>等待登录...</span>`;} else if (atH) {atEl.innerHTML = `<span class="rmj-badge on">${atH}</span>${refreshIcon}`;} else {atEl.innerHTML = `<a class="rmj-badge off" href="javascript:void(0)" id="rmj-at-bind">去绑定 →</a>`;}const cfBind = modalEl.querySelector('#rmj-cf-bind');if (cfBind) cfBind.onclick = () => { startCfPoll(); };const cfRefresh = modalEl.querySelector('#rmj-cf .rmj-refresh-wrap');if (cfRefresh) {cfRefresh.onclick = () => {window.open('https://codeforces.com/enter', '_blank');startCfPoll();};}const atBind = modalEl.querySelector('#rmj-at-bind');if (atBind) {atBind.onclick = (e) => { e.preventDefault(); captureAtHandle(); };}const atRefresh = modalEl.querySelector('#rmj-at .rmj-refresh-wrap');if (atRefresh) atRefresh.onclick = () => captureAtHandle();const syncToggle = modalEl.querySelector('#rmj-disable-sync');if (syncToggle) {const isDisabled = isSyncDisabled();syncToggle.checked = !isDisabled;if (isSpecialAccount()) {syncToggle.checked = false;syncToggle.disabled = true;syncToggle.title = '特殊账号无法修改同步设置';}syncToggle.onchange = async () => {if (isSpecialAccount()) {syncToggle.checked = false;return;}GM_setValue(CACHE_AT, '[]');GM_setValue(CACHE_CF, '[]');GM_setValue(LAST_UPDATE_AT, '0');GM_setValue('cf-0last-update', '0');updateListIcons();updateProblemBadge();};}};const switchModalPage = (idx) => {if (!modalEl || idx === modalPage) return;const pagesContainer = modalEl.querySelector('.rmj-pages');const allPages = modalEl.querySelectorAll('.rmj-page');const targetPage = allPages[idx];const dots = modalEl.querySelectorAll('.rmj-dot');const prevBtn = modalEl.querySelector('.rmj-prev');const nextBtn = modalEl.querySelector('.rmj-next');allPages.forEach((p, i) => p.classList.toggle('active', i === idx));if (targetPage && pagesContainer) {pagesContainer.style.height = targetPage.scrollHeight + 'px';}dots.forEach((d, i) => d.classList.toggle('active', i === idx));prevBtn.disabled = idx === 0;nextBtn.disabled = idx === dots.length - 1;modalPage = idx;if (idx === 1 && !GM_getValue('at-handle', '') && !atCapturing) {fetchAtHandle().then((h) => {if (h) {const stored = GM_getValue('at-handle', '');if (stored !== h) GM_setValue('at-handle', h);updateModal();}});}};const showModal = (page = 0) => {if (!modalEl) buildModal();modalPage = page;const pagesContainer = modalEl.querySelector('.rmj-pages');const allPages = modalEl.querySelectorAll('.rmj-page');const targetPage = allPages[page];const dots = modalEl.querySelectorAll('.rmj-dot');const prevBtn = modalEl.querySelector('.rmj-prev');const nextBtn = modalEl.querySelector('.rmj-next');allPages.forEach((p, i) => p.classList.toggle('active', i === page));requestAnimationFrame(() => {if (targetPage && pagesContainer) {pagesContainer.style.height = targetPage.scrollHeight + 'px';}});dots.forEach((d, i) => d.classList.toggle('active', i === page));prevBtn.disabled = page === 0;nextBtn.disabled = page === dots.length - 1;modalEl.style.pointerEvents = '';modalEl.classList.add('show');};const hideModal = () => {if (!modalEl) return;modalEl.classList.remove('show');modalEl.style.pointerEvents = 'none';};const checkVersion = () => {if (GM_getValue('rmj-version-shown', '') !== VERSION) {setTimeout(() => showModal(0), 500);}};const injectHomeButton = () => {if (location.pathname !== '/' || document.querySelector('.rmj-trigger')) return;waitFor('.right', (nav) => {if (nav.dataset.rmj) return;nav.dataset.rmj = '1';const btn = document.createElement('button');btn.className = 'rmj-trigger';btn.innerHTML = `<img src="https://cdn.luogu.com.cn/upload/image_hosting/yy27itbl.png">GenGen RMJ`;btn.onclick = () => showModal(1);nav.parentElement.insertBefore(btn, nav);});};const initProblemPage = () => {const p = location.pathname;if (!p.startsWith('/problem/CF') && !p.startsWith('/problem/AT')) return;if (currentProblemPath === p && problemObserver) return;currentProblemPath = p;const myPath = p;const myGen = ++problemGen;const rmj = p.startsWith('/problem/CF') ? '1' : '2';const pid = p.split('/problem/')[1];if (!pid) return;if (problemObserver) { problemObserver.disconnect(); problemObserver = null; }waitFor('.side', (side) => {if (myGen !== problemGen || currentProblemPath !== myPath) return;problemObserver = new MutationObserver(() => {side.querySelectorAll('a[href*="/record/list?pid="]').forEach((link) => {if (link.dataset.rmjHook) return;link.dataset.rmjHook = '1';link.addEventListener('click', (e) => {if (e.button !== 0) return;e.preventDefault();e.stopImmediatePropagation();const u = new URL('/record/list', location.origin);const sp = new URLSearchParams(location.search);for (const [k, v] of sp) u.searchParams.set(k, v);u.searchParams.set('pid', pid);u.searchParams.set('rmj', rmj);location.href = u.toString();}, true);link.addEventListener('mousedown', (e) => {if (e.button !== 1) return;const u = new URL('/record/list', location.origin);const sp = new URLSearchParams(location.search);for (const [k, v] of sp) u.searchParams.set(k, v);u.searchParams.set('pid', pid);u.searchParams.set('rmj', rmj);link.href = u.toString();}, true);});updateProblemBadge();});problemObserver.observe(side, { childList: true, subtree: true });});updateProblemBadge();startProblemPoll();};const injectRecordListSelector = () => {if (!location.pathname.startsWith('/record/list')) return;const myGen = problemGen;waitFor('#app > div.main-container.lside-nav > div > main > div > div:nth-child(1) > section:nth-child(2) > div > div > div.text.lform-size-middle',(b) => {if (myGen !== problemGen) return;const cur = new URLSearchParams(location.search).get('rmj') || '';let w = document.querySelector('.rmj-sel');if (w) {const btn = w.querySelector('.rmj-sel-btn');const menu = w.querySelector('.rmj-sel-menu');if (btn && menu) {const act = menu.querySelector(`li[data-value="${cur}"]`);if (act && btn.textContent !== act.textContent) {btn.textContent = act.textContent;}}return;}w = document.createElement('span');w.className = 'rmj-sel';w.innerHTML = `<button class="rmj-sel-btn">洛谷</button><ul class="rmj-sel-menu"><li data-value="">洛谷</li><li data-value="1">Codeforces</li><li data-value="2">AtCoder</li></ul>`;b.after(w);const btn = w.querySelector('.rmj-sel-btn');const menu = w.querySelector('.rmj-sel-menu');btn.addEventListener('click', (e) => {e.stopPropagation();w.classList.toggle('open');menu.classList.toggle('open');});menu.querySelectorAll('li').forEach((li) => {li.addEventListener('click', (e) => {e.stopPropagation();const val = li.dataset.value;btn.textContent = li.textContent;w.classList.remove('open');menu.classList.remove('open');const p = new URLSearchParams(location.search);if (val) p.set('rmj', val);else p.delete('rmj');location.search = p.toString();});});document.addEventListener('click', () => {w.classList.remove('open');menu.classList.remove('open');});const act = menu.querySelector(`li[data-value="${cur}"]`);if (act) btn.textContent = act.textContent;});};const handleRoute = () => {if (!isLuogu()) return;const path = location.pathname;ThemeStore.extractWithRetry(15, 250);if (path === '/') injectHomeButton();if (path.startsWith('/problem/CF') || path.startsWith('/problem/AT')) {initProblemPage();} else {stopProblemPoll();teardownProblemObserver();}if (path.startsWith('/training') || path.startsWith('/problem/list')) {startListPoll();} else {stopListPoll();}if (path.startsWith('/record/list')) {injectRecordListSelector();}};const init = () => {if (!isLuogu()) return;checkVersion();handleRoute();addEventListener('beforeunload', () => { stopListPoll(); stopProblemPoll(); });};return { init, handleRoute, hideModal, captureCfHandle };})();// 洛谷记录详情页(DET)const RecordDetail = (() => {const _gmGet = GM_getValue;const _gmReq = GM_xmlhttpRequest;const VALID = [/^https:\/\/www\.luogu\.com\.cn\/record\/cf\/[^/]+\/[^/?#]+/,/^https:\/\/www\.luogu\.com\.cn\/record\/at\/[^/]+\/[^/?#]+/,];const CF2LG = {OK: 12, WRONG_ANSWER: 6, TIME_LIMIT_EXCEEDED: 5, MEMORY_LIMIT_EXCEEDED: 4,OUTPUT_LIMIT_EXCEEDED: 3, RUNTIME_ERROR: 7, COMPILATION_ERROR: 2, TESTING: 1, WAITING: 0};const FINAL_CF = new Set(['OK', 'WRONG_ANSWER', 'COMPILATION_ERROR', 'RUNTIME_ERROR','TIME_LIMIT_EXCEEDED', 'MEMORY_LIMIT_EXCEEDED', 'OUTPUT_LIMIT_EXCEEDED']);GM_addStyle(`#rmj-det-overlay.rmj-ovl-base{z-index:2147483647!important}#rmj-det-card{width:420px!important;max-width:90vw!important}`);const gmJson = (url) => new Promise((ok, no) => {_gmReq({method: 'GET', url, timeout: 15000, anonymous: true,onload: (r) => { try { ok(JSON.parse(r.responseText)); } catch (e) { no(e); } },onerror: () => no(new Error('网络错误')),ontimeout: () => no(new Error('请求超时'))});});const gmText = (url) => new Promise((ok, no) => {_gmReq({method: 'GET', url, timeout: 15000, anonymous: true,onload: (r) => r.status === 200 ? ok(r.responseText) : no(new Error('状态码 ' + r.status)),onerror: () => no(new Error('网络错误')),ontimeout: () => no(new Error('请求超时'))});});let lastKey = '';let generation = 0;const timers = Timers();const buildLoader = () => {const el = document.createElement('div');el.id = 'rmj-det-overlay';el.className = 'rmj-ovl-base';el.innerHTML = `<div class="rmj-ly rmj-ly-c"></div><div class="rmj-ly rmj-ly-i"></div><div id="rmj-det-card" class="rmj-ovl-card"><h2>正在加载提交记录</h2><p>正在从 CF/AT 获取数据</p><div class="rmj-ovl-spin"></div></div>`;ThemeStore.applyTo(el);return el;};// 未绑定提示const showBindError = (bindName) => {const el = document.createElement('div');el.id = 'rmj-det-overlay';el.className = 'rmj-ovl-base';el.innerHTML = `<div class="rmj-ly rmj-ly-c"></div><div class="rmj-ly rmj-ly-i"></div><div id="rmj-det-card" class="rmj-ovl-card"><h2>账号未绑定</h2><p>请先在 GenGen RMJ 面板中绑定 ${bindName} 账号</p><a href="https://www.luogu.com.cn/" style="margin-top:8px!important;padding:8px 22px !important;background:#66ccff;color:#fff;text-decoration:none;border-radius:6px;font-size:14px;display:inline-block;">前往洛谷主页绑定</a></div>`;ThemeStore.applyTo(el);(document.documentElement || document.body).appendChild(el);};const destroy = () => {generation++;timers.clearAll();const mask = document.getElementById('rmj-det-overlay');if (mask) mask.remove();lastKey = '';};const init = () => {if (!VALID.some((r) => r.test(location.href))) {if (lastKey) destroy();return;}const m = location.pathname.match(/\/record\/(cf|at)\/([^/]+)\/([^/?#]+)/);if (!m) return;const [, plat, cid, sid] = m;const key = `${plat}/${cid}/${sid}`;if (lastKey === key) return;destroy();lastKey = key;const myGen = generation;const isCFPage = plat === 'cf';const isATPage = plat === 'at';// 未绑定则拒绝查看const bindKey = isCFPage ? 'cf-handle' : 'at-handle';const bindName = isCFPage ? 'Codeforces' : 'AtCoder';if (!_gmGet(bindKey, '')) {showBindError(bindName);return;}const handle = _gmGet('cf-handle', '') || _gmGet('rmj-cf-handle', '') || '';const code = _gmGet(`{${cid},${sid}}`, '');const titleTimer = timers.iv(() => { document.title = 'GenGen RMJ 加载中'; }, 100);const mask = buildLoader();(document.documentElement || document.body || document).appendChild(mask);let cachedTpl = null;const fetchTemplate = async () => {if (cachedTpl) return cachedTpl;return new Promise((ok, no) => {_gmReq({method: 'GET', url: 'https://www.luogu.com.cn/record/290510067', timeout: 15000,onload: (r) => {if (r.status === 200) { cachedTpl = r.responseText; ok(cachedTpl); }else no(new Error('模板获取失败'));},onerror: () => no(new Error('模板网络错误')),ontimeout: () => no(new Error('模板请求超时'))});});};async function findCF() {let url = `https://codeforces.com/api/contest.status?contestId=${encodeURIComponent(cid)}&from=1&count=100`;if (handle) url += `&handle=${encodeURIComponent(handle)}`;const d = await gmJson(url);if (d.status !== 'OK') throw new Error('CF ' + d.status);return (d.result || []).find((x) => String(x.id) === sid) || null;}function parseATStatus(text) {if (!text) return 'TESTING';text = text.trim();if (text === 'AC') return 'OK';if (text === 'WA') return 'WRONG_ANSWER';if (text === 'TLE' || text.includes('TLE')) return 'TIME_LIMIT_EXCEEDED';if (text === 'MLE') return 'MEMORY_LIMIT_EXCEEDED';if (text === 'OLE') return 'OUTPUT_LIMIT_EXCEEDED';if (text === 'RE') return 'RUNTIME_ERROR';if (text === 'CE') return 'COMPILATION_ERROR';if (text === 'WJ') return 'WAITING';if (text.includes('WA')) return 'WRONG_ANSWER';return 'TESTING';}async function findAT() {const url = `https://atcoder.jp/contests/${cid}/submissions/${sid}`;const html = await gmText(url);const doc = new DOMParser().parseFromString(html, 'text/html');const metaTable = doc.querySelector('table.table-bordered');const metaRows = metaTable ? metaTable.querySelectorAll('tr') : [];const meta = {};metaRows.forEach((row) => {const th = row.querySelector('th');const td = row.querySelector('td');if (th && td) meta[th.textContent.trim()] = td.textContent.trim();});const codeEl = doc.querySelector('#submission-code');const sourceCode = codeEl ? codeEl.textContent : '';const tables = doc.querySelectorAll('table.table-bordered');const cases = [];let passedCount = 0;let caseTable = null;for (const t of tables) {const header = t.querySelector('thead th, tr th');if (header && (header.textContent.includes('Case Name') || header.textContent.includes('Status'))) {caseTable = t;break;}}if (caseTable) {caseTable.querySelectorAll('tbody tr').forEach((row, index) => {const tds = row.querySelectorAll('td');if (tds.length >= 4) {const statusText = tds[1].textContent.trim();const timeMatch = tds[2].textContent.trim().match(/(\d+)/);const memMatch = tds[3].textContent.trim().match(/(\d+)/);const verdict = parseATStatus(statusText);if (verdict === 'OK') passedCount++;cases.push({id: `${index + 1}`,status: verdict,time: timeMatch ? parseInt(timeMatch[1]) : null,memKB: memMatch ? parseInt(memMatch[1]) : null});}});}let overallVerdict = parseATStatus(meta['Status'] || '');if (overallVerdict === 'OK' && passedCount < cases.length && cases.length > 0) {overallVerdict = 'TESTING';}const timeMatch = (meta['Exec Time'] || '').match(/(\d+)/);const memMatch = (meta['Memory'] || '').match(/(\d+)/);const taskText = meta['Task'] || '';let taskIndex = 'a';const taskLink = metaTable ? metaTable.querySelector('a[href*="/tasks/"]') : null;if (taskLink) {const linkMatch = (taskLink.getAttribute('href') || '').match(/\/tasks\/[^_]+_(.+)$/i);if (linkMatch) taskIndex = linkMatch[1].toLowerCase();} else {const textMatch = taskText.match(/^([A-Za-z0-9]+)/);if (textMatch) taskIndex = textMatch[1].toLowerCase();}let submitTime = 0;const timeStr = meta['Submission Time'] || '';if (timeStr) {const tm = timeStr.match(/^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})([+-]\d{2})(\d{2})$/);submitTime = tm? Math.floor(new Date(`${tm[1]}T${tm[2]}${tm[3]}:${tm[4]}`).getTime() / 1000): (Math.floor(new Date(timeStr).getTime() / 1000) || 0);}return {isAT: true, verdict: overallVerdict, passedTestCount: passedCount,timeConsumedMillis: timeMatch ? parseInt(timeMatch[1]) : 0,memoryConsumedBytes: memMatch ? parseInt(memMatch[1]) * 1024 : 0,problem: { name: taskText, index: taskIndex }, sourceCode, cases,creationTimeSeconds: submitTime};}function buildCases(sub, time, memKB) {if (sub.isAT) {return sub.cases.map((c, index) => ({id: index,status: CF2LG[c.status] ?? 0,time: c.time ?? 0,memory: c.memKB ?? 0,score: 1,signal: 0,exitCode: 0,description: '',subtaskID: 0}));}const lgCode = CF2LG[sub.verdict] ?? 0;const isAC = sub.verdict === 'OK';const isCE = sub.verdict === 'COMPILATION_ERROR';const passed = sub.passedTestCount ?? 0;if (isCE) return [];const idNum = isAC ? (passed > 0 ? passed - 1 : 0) : passed;let status = isAC ? 12 : lgCode;if (sub.verdict === 'TESTING') status = 1;return [{id: idNum, status,time: time ?? 0, memory: memKB ?? 0,score: 100, signal: 0, exitCode: 0,description: '', subtaskID: 0}];}function buildHtml(tpl, sub) {const FE_RE = /<script\s+id="lentille-context"\s+type="application\/json">([\s\S]*?)<\/script>/i;const fm = tpl.match(FE_RE);if (!fm) return tpl;let data;try { data = JSON.parse(fm[1]); } catch (e) { return tpl; }const rec = data?.data?.record;if (!rec) return tpl;const cu = data?.data?.user || data?.user;if (rec.user && cu) {Object.assign(rec.user, {uid: cu.uid, name: cu.name, avatar: cu.avatar,color: cu.color || '', slogan: cu.slogan || ''});}if (isATPage && sub && sub.sourceCode) {rec.sourceCode = sub.sourceCode;rec.sourceCodeLength = sub.sourceCode.length;} else if (code) {rec.sourceCode = code;rec.sourceCodeLength = code.length;} else {rec.sourceCode = '// 未找到该提交的源代码\n// 请前往原站查看';rec.sourceCodeLength = 0;}if ((isCFPage || isATPage) && sub) {const lgCode = CF2LG[sub.verdict] ?? 0;const isFinal = FINAL_CF.has(sub.verdict);const time = isFinal ? (sub.timeConsumedMillis ?? 0) : 0;const memKB = isFinal ? Math.round((sub.memoryConsumedBytes ?? 0) / 1024) : 0;if (rec.problem && sub.problem) {if (isCFPage) {rec.problem.pid = `CF${cid}${sub.problem.index}`;rec.problem.type = 'CF';} else if (isATPage) {rec.problem.pid = `AT_${cid}_${sub.problem.index}`;rec.problem.type = 'AT';}rec.problem.name = sub.problem.name;delete rec.problem.title;}rec.status = lgCode;rec.time = time;rec.memory = memKB;rec.id = Number(sid) || rec.id;if (sub.creationTimeSeconds) rec.submitTime = sub.creationTimeSeconds;if (rec.detail?.compileResult) {rec.detail.compileResult.success = sub.verdict !== 'COMPILATION_ERROR';}const cases = buildCases(sub, time, memKB);if (rec.detail?.judgeResult) {rec.detail.judgeResult.subtasks = [{id: 0, score: null, status: lgCode,testCases: cases, judger: '',time, memory: memKB}];rec.detail.judgeResult.finishedCaseCount = cases.length;rec.detail.judgeResult.status = lgCode;rec.detail.judgeResult.time = time;rec.detail.judgeResult.memory = memKB;rec.detail.judgeResult.score = null;}}const newJsonStr = JSON.stringify(data).replace(/</g, '\\u003c').replace(/\//g, '\\/');return tpl.replace(FE_RE, `<script id="lentille-context" type="application/json">${newJsonStr}</script>`);}async function renderPage(sub) {if (myGen !== generation) return;const tpl = await fetchTemplate().catch(() => null);if (!tpl || myGen !== generation) return;const doc = new DOMParser().parseFromString(buildHtml(tpl, sub), 'text/html');document.replaceChild(doc.documentElement, document.documentElement);document.querySelectorAll('script').forEach((oldScript) => {const newScript = document.createElement('script');Array.from(oldScript.attributes).forEach((attr) => newScript.setAttribute(attr.name, attr.value));newScript.textContent = oldScript.textContent;oldScript.parentNode.replaceChild(newScript, oldScript);});}(async () => {const updateCache = (sub) => {if (!sub || myGen !== generation) return;if (isCFPage) {let cache = [];try { cache = JSON.parse(GM_getValue(CACHE_CF, '[]')); if (!Array.isArray(cache)) cache = []; }catch { cache = []; }const item = {id: String(sid),taskDisplay: `CF${cid}${sub.problem.index} - ${sub.problem.name}`,status: sub.verdict || 'Waiting',timestamp: (sub.creationTimeSeconds || 0) * 1000,submitUrl: `https://www.luogu.com.cn/record/cf/${cid}/${sid}`,luoguUrl: `https://www.luogu.com.cn/problem/CF${cid}${sub.problem.index}`,passedTestCount: sub.passedTestCount};const idx = cache.findIndex((c) => c.id === String(sid));if (idx !== -1) cache[idx] = { ...cache[idx], ...item };else cache.unshift(item);cache.sort((a, b) => Number(b.id) - Number(a.id));GM_setValue(CACHE_CF, JSON.stringify(cache));GM_setValue(LAST_UPDATE_CF, Date.now());} else if (isATPage) {let cache = [];try { cache = JSON.parse(GM_getValue(CACHE_AT, '[]')); if (!Array.isArray(cache)) cache = []; }catch { cache = []; }const AT_VERDICT_MAP = {OK: 'AC', WRONG_ANSWER: 'WA', TIME_LIMIT_EXCEEDED: 'TLE',MEMORY_LIMIT_EXCEEDED: 'MLE', OUTPUT_LIMIT_EXCEEDED: 'OLE',RUNTIME_ERROR: 'RE', COMPILATION_ERROR: 'CE', WAITING: 'WJ', TESTING: 'WJ'};const atStatus = AT_VERDICT_MAP[sub.verdict] || 'WJ';const taskKey = `${cid}_${sub.problem.index}`;const item = {id: String(sid), taskKey,taskDisplay: `${taskKey} - ${sub.problem.index.toUpperCase()} - ${sub.problem.name}`,status: atStatus,submitUrl: `https://atcoder.jp/contests/${cid}/submissions/${sid}`,luoguUrl: `https://www.luogu.com.cn/problem/AT_${taskKey}`,timestamp: (sub.creationTimeSeconds || 0) * 1000,isFinal: FINAL_AT.has(atStatus)};const idx = cache.findIndex((c) => c.id === String(sid));if (idx !== -1) cache[idx] = { ...cache[idx], ...item };else cache.unshift(item);cache.sort((a, b) => Number(b.id) - Number(a.id));GM_setValue(CACHE_AT, JSON.stringify(cache));GM_setValue(LAST_UPDATE_AT, Date.now());}};const cfDomainPath = Number(cid) > 100000 ? 'gym' : 'contest';const origUrl = isCFPage? `https://codeforces.com/${cfDomainPath}/${cid}/submission/${sid}`: `https://atcoder.jp/contests/${cid}/submissions/${sid}`;let sub = null;try {sub = isCFPage ? await findCF() : (isATPage ? await findAT() : null);} catch (e) {if (myGen !== generation) return;if (isATPage) { timers.clear(titleTimer); location.replace(origUrl); return; }}if (myGen !== generation) return;if (isCFPage && sub === null) {timers.clear(titleTimer);location.replace(origUrl);return;}if (sub) updateCache(sub);timers.clear(titleTimer);// 已拿到结果直接渲染一次await renderPage(sub);if (myGen !== generation) return;let currentSub = sub;let atWaitPollingId = null;timers.iv(() => {if (myGen !== generation) return;const m2 = document.getElementById('rmj-det-overlay');if (m2 && (document.querySelector('#app') || document.querySelector('.lfe-body'))) m2.remove();const hasCode = (isATPage && currentSub && currentSub.sourceCode) || code;if (!hasCode) {const vals = document.querySelectorAll('.value.lfe-caption');if (vals.length >= 2 && vals[1].textContent !== '-') vals[1].textContent = '-';const ce = document.querySelector('pre code');if (ce) {const pre = ce.closest('pre');if (pre) pre.outerHTML = `<div class="card padding-default" style="text-align:center;color:#e74c3c;padding:40px;display:flex;flex-direction:column;align-items:center;justify-content:center;"><div>本代码非 GenGen RMJ 提交,无法查看</div><a href="${origUrl}" target="_blank" style="margin-top:8px;color:#3498db;text-decoration:none;">前往原站</a></div>`;}}const card = document.querySelectorAll('.l-card')[1];if (card && !card.querySelector('.rmj-orig-link')) {const a = document.createElement('a');a.href = origUrl;a.target = '_blank';a.className = 'rmj-orig-link';a.textContent = '前往原站';a.style.cssText = 'display:block;text-align:center;margin-top:16px;color:#3498db;text-decoration:none;';card.appendChild(a);}if (currentSub && currentSub.verdict !== 'COMPILATION_ERROR') {const tcs = document.querySelectorAll('.test-case');if (currentSub.isAT) {tcs.forEach((tc, idx) => {const idEl = tc.querySelector('.id');const target = `#${idx + 1}`;if (idEl && idEl.textContent !== target) idEl.textContent = target;});} else {const passed = currentSub.passedTestCount ?? 0;const idNum = currentSub.verdict === 'OK' ? (passed > 0 ? passed : 1) : passed + 1;const target = `#${idNum}`;tcs.forEach((tc) => {const idEl = tc.querySelector('.id');if (idEl && idEl.textContent !== target) idEl.textContent = target;});}}// AT 未返回完整测试点时的等待提示if (atWaitPollingId !== null) {const h5 = document.querySelector('#app > div.main-container.lside-nav > div > main > div > div > div.main > div > section > div > h5');if (h5 && h5.textContent !== '正在等待 AtCoder 评测完成') {h5.textContent = '正在等待 AtCoder 评测完成';}const testWrap = document.querySelector('.test-case-wrap');if (testWrap && !document.getElementById('rmj-at-wait-msg')) {const waitMsg = document.createElement('div');waitMsg.id = 'rmj-at-wait-msg';waitMsg.textContent = '正在等待 AtCoder 完整评测完毕';waitMsg.style.cssText = 'text-align:center;padding:12px;color:#666;font-size:14px;';testWrap.appendChild(waitMsg);}}}, 500);if ((!isCFPage && !isATPage) || !sub) return;const startAtWaitPolling = () => {if (atWaitPollingId !== null || !isATPage) return;atWaitPollingId = timers.iv(async () => {if (myGen !== generation) return;try {const s = await findAT();if (myGen !== generation) return;if (s && s.cases.length > 0) {timers.clear(atWaitPollingId);atWaitPollingId = null;const msg = document.getElementById('rmj-at-wait-msg');if (msg) msg.remove();currentSub = s;await renderPage(s);updateCache(s);}} catch (e) { /* ignore */ }}, 5000);};if (isATPage && sub.cases.length === 0 && sub.verdict !== 'COMPILATION_ERROR' && FINAL_CF.has(sub.verdict)) {startAtWaitPolling();}if (!FINAL_CF.has(sub.verdict)) {let polling = false;const intervalId = timers.iv(async () => {if (myGen !== generation) return;if (polling) return;polling = true;try {const s = isCFPage ? await findCF() : await findAT();if (myGen !== generation) return;if (s) {currentSub = s;updateCache(s);if (FINAL_CF.has(s.verdict) && s.isAT && s.cases.length === 0 && s.verdict !== 'COMPILATION_ERROR') {startAtWaitPolling();}if (FINAL_CF.has(s.verdict)) {timers.clear(intervalId);await renderPage(s);}}} catch (e) { /* ignore */ }finally { polling = false; }}, 3000);}})();};return { init, destroy };})();// 洛谷记录列表页const RecordList = (() => {let syncStarted = false;let pageKey = '';let pageGen = 0;const timers = Timers();const req = (url, opts = {}) => new Promise((res, rej) => {const t = setTimeout(() => rej(new Error('请求超时')), 8000);GM_xmlhttpRequest({method: 'GET', url, ...opts,onload: (r) => { clearTimeout(t); res(r); },onerror: (e) => { clearTimeout(t); rej(e); }});});const getCache = (key) => {try {const p = JSON.parse(GM_getValue(key, '[]'));if (!Array.isArray(p)) return [];return p.map((s) => {if (s.submitUrl) {let m = s.submitUrl.match(/atcoder\.jp\/contests\/([^/]+)\/submissions\/(\d+)/);if (m) s.submitUrl = `https://www.luogu.com.cn/record/at/${m[1]}/${m[2]}`;else {m = s.submitUrl.match(/codeforces\.com\/(?:contest|gym)\/(\d+)\/submission\/(\d+)/);if (m) s.submitUrl = `https://www.luogu.com.cn/record/cf/${m[1]}/${m[2]}`;}}if (s.luoguUrl) {let m = s.luoguUrl.match(/atcoder\.jp\/contests\/[^/]+\/tasks\/([^/\s?#]+)/);if (m) s.luoguUrl = `https://www.luogu.com.cn/problem/AT_${m[1]}`;else {m = s.luoguUrl.match(/codeforces\.com\/(?:problemset\/problem|(?:contest|gym)\/\d+\/problem)\/(\d+)\/([A-Za-z]\d?)/);if (m) s.luoguUrl = `https://www.luogu.com.cn/problem/CF${m[1]}${m[2]}`;}}return s;});} catch { return []; }};const saveCache = (key, c) => GM_setValue(key, JSON.stringify(Array.isArray(c) ? c : []));const markUpdated = (key) => GM_setValue(key, Date.now());const crawlATContest = async (contestId, existingCache = []) => {if (!contestId) return existingCache;try {const r = await req(`https://atcoder.jp/contests/${contestId}/submissions/me`);if (r.status !== 200) return existingCache;const doc = new DOMParser().parseFromString(r.responseText, 'text/html');const rows = Array.from(doc.querySelectorAll('table.table tbody tr'));if (!rows.length) return existingCache;const cacheMap = new Map(existingCache.map((s) => [s.id, s]));let hasNew = false;for (const row of rows) {const cells = Array.from(row.querySelectorAll('td'));if (cells.length < 7) continue;const tl = cells[1]?.querySelector('a');const tHref = tl?.href || '';const tName = tl?.innerText?.trim() || '';const tKey = tHref.match(/\/tasks\/([^/\s]+)/)?.[1] || '';let rs = 'Waiting';for (const c of cells) {const l = c.querySelector('.label');if (l) { rs = l.innerText.trim(); break; }}const da = cells[cells.length - 1]?.querySelector('a.submission-details-link');if (!da?.href) continue;const sid = da.href.split('/').pop();const isF = FINAL_AT.has(rs);const prev = cacheMap.get(sid);if (!prev || prev.status !== rs) {cacheMap.set(sid, {id: sid, taskKey: tKey,taskDisplay: `${tKey} - ${tName}`,status: rs,submitUrl: `https://www.luogu.com.cn/record/at/${contestId}/${sid}`,luoguUrl: `https://www.luogu.com.cn/problem/AT_${tKey}`,timestamp: prev?.timestamp || Date.now(),isFinal: isF});hasNew = true;} else if (isF && !prev.isFinal) {prev.isFinal = true;prev.status = rs;hasNew = true;}}if (hasNew) {return Array.from(cacheMap.values()).sort((a, b) => Number(b.id) - Number(a.id));}return existingCache;} catch (e) {LOG('AT 爬取失败', e.message || e);return existingCache;}};const fetchCFData = async (handle) => {const sr = await req(`https://codeforces.com/api/user.status?handle=${encodeURIComponent(handle)}&from=1`);if (sr.status !== 200) throw new Error('CF API 状态码非 200');const d = JSON.parse(sr.responseText);if (d.status !== 'OK') throw new Error('CF API 状态非 OK');const seen = new Set();return (d.result || []).filter((s) => {if (seen.has(s.id)) return false;seen.add(s.id);return true;}).map((s) => ({id: String(s.id),taskDisplay: `CF${s.contestId}${s.problem.index} - ${s.problem.name}`,status: s.verdict || 'Waiting',timestamp: s.creationTimeSeconds * 1000,submitUrl: `https://www.luogu.com.cn/record/cf/${s.contestId}/${s.id}`,luoguUrl: `https://www.luogu.com.cn/problem/CF${s.contestId}${s.problem.index}`,passedTestCount: s.passedTestCount}));};const fetchATProblems = async () => {try {const r = await req('https://kenkoooo.com/atcoder/resources/problems.json');if (r.status !== 200) return new Map();const m = new Map();for (const p of JSON.parse(r.responseText)) {if (p.id) m.set(p.id, { index: p.problem_index || '', name: p.name || '' });}return m;} catch { return new Map(); }};const fmtATTask = (pid, pMap) => {const p = pMap.get(pid);if (p?.name && p.index) return `${pid} - ${p.index} - ${p.name}`;const parts = pid.split('_');const c = parts[0] || '';const i = parts[1] ? parts[1].toUpperCase() : '';return `${pid} - ${i ? `${c.toUpperCase()} ${i}` : pid}`;};const fetchATSubmissions = async (pMap, uid) => {try {if (!uid) return [];const sr = await req(`https://kenkoooo.com/atcoder/atcoder-api/v3/user/submissions?user=${encodeURIComponent(uid)}&from_second=0`);if (sr.status !== 200) return [];const subs = JSON.parse(sr.responseText);if (!Array.isArray(subs)) return [];return subs.map((s) => ({id: String(s.id),taskKey: s.problem_id,taskDisplay: fmtATTask(s.problem_id, pMap),status: s.result,submitUrl: `https://www.luogu.com.cn/record/at/${s.contest_id}/${s.id}`,luoguUrl: `https://www.luogu.com.cn/problem/AT_${s.problem_id}`,timestamp: s.epoch_second * 1000,isFinal: FINAL_AT.has(s.result)}));} catch (e) {LOG('Kenkoooo 拉取失败', e);return [];}};const fetchATData = async (uid) => {const pMap = await fetchATProblems();const subs = await fetchATSubmissions(pMap, uid);return subs.map((s) => ({ ...s, taskDisplay: fmtATTask(s.taskKey, pMap) }));};let isCFSyncing = false;let isATSyncing = false;const syncCF = async (options = {}) => {if (isCFSyncing) return;isCFSyncing = true;try {const { render = false, renderFn = null, mainDiv = null, force = false } = options;const cache = getCache(CACHE_CF);const lastUpdate = GM_getValue(LAST_UPDATE_CF, 0);const isStale = (Date.now() - lastUpdate) > SYNC_INTERVAL_MS;if (!force && cache.length > 0 && !isStale) {if (render && renderFn && mainDiv) renderFn(cache, mainDiv);return;}const handle = GM_getValue('cf-handle', '');if (!handle) {LOG('未找到 CF 用户名');return;}const subs = await fetchCFData(handle);saveCache(CACHE_CF, subs);markUpdated(LAST_UPDATE_CF);if (render && renderFn && mainDiv) renderFn(subs, mainDiv);} catch (e) {LOG('CF 同步失败', e.message || e);} finally {isCFSyncing = false;}};const syncAT = async (options = {}) => {if (isATSyncing) return;isATSyncing = true;try {const { render = false, renderFn = null, mainDiv = null, force = false } = options;const cache = getCache(CACHE_AT);const lastUpdate = GM_getValue(LAST_UPDATE_AT, 0);const isStale = (Date.now() - lastUpdate) > SYNC_INTERVAL_MS;if (!force && cache.length > 0 && !isStale) {if (render && renderFn && mainDiv) renderFn(cache, mainDiv);return;}const atHandle = GM_getValue('at-handle', '');if (!atHandle) {LOG('未找到 AT 用户名');return;}const subs = await fetchATData(atHandle);const mm = new Map();for (const s of [...subs, ...cache]) {if (!mm.has(s.id)) mm.set(s.id, s);}const merged = Array.from(mm.values()).sort((a, b) => Number(b.id) - Number(a.id));saveCache(CACHE_AT, merged);markUpdated(LAST_UPDATE_AT);if (render && renderFn && mainDiv) renderFn(merged, mainDiv);} catch (e) {LOG('AT 同步失败', e.message || e);} finally {isATSyncing = false;}};const startBackgroundSync = () => {if (syncStarted) return;syncStarted = true;let disableSync = GM_getValue('rmj-disable-sync', false) === true;try {const params = new URLSearchParams(location.search);if (params.get('rmj-disable-sync') === 'true') disableSync = true;} catch { /* ignore */ }if (!disableSync) {syncCF({ render: false });syncAT({ render: false });} else {LOG('同步已禁用,仅显示模式');}};const destroy = () => {pageGen++;timers.clearAll();pageKey = '';};const init = async () => {if (!isLuogu()) return;startBackgroundSync();const URL_PATH = location.pathname;if (!/^\/record\/list/.test(URL_PATH)) {if (pageKey) destroy();return;}const params = new URLSearchParams(window.location.search);const rmj = params.get('rmj');if (!['1', '2'].includes(rmj)) {if (pageKey) destroy();return;}const key = `${URL_PATH}?rmj=${rmj}`;if (pageKey === key) return;destroy();pageKey = key;const myGen = pageGen;const pid = params.get('pid') || '';const contest = params.get('contest') || '';const isCFMode = rmj === '1';const isATMode = rmj === '2';const disableSync = GM_getValue('rmj-disable-sync', false) === true ||params.get('rmj-disable-sync') === 'true';const STATUS_MAP = isCFMode ? {OK: ['Accepted', 'cf-status-accepted'], WRONG_ANSWER: ['Wrong Answer', 'cf-status-wrong'],COMPILATION_ERROR: ['Compilation Error', 'cf-status-ce'], RUNTIME_ERROR: ['Runtime Error', 'cf-status-re'],TIME_LIMIT_EXCEEDED: ['Time Limit Exceeded', 'cf-status-limit'], MEMORY_LIMIT_EXCEEDED: ['Memory Limit Exceeded', 'cf-status-limit'],OUTPUT_LIMIT_EXCEEDED: ['Output Limit Exceeded', 'cf-status-limit'], TESTING: ['Running', 'cf-status-running']} : {AC: ['Accepted', 'cf-status-accepted'], WA: ['Wrong Answer', 'cf-status-wrong'],CE: ['Compilation Error', 'cf-status-ce'], RE: ['Runtime Error', 'cf-status-re'],TLE: ['Time Limit Exceeded', 'cf-status-limit'], MLE: ['Memory Limit Exceeded', 'cf-status-limit'],OLE: ['Output Limit Exceeded', 'cf-status-limit'], IE: ['Internal Error', 'cf-status-ce']};const style = document.createElement('style');style.textContent = `.cf-card{display:flex;align-items:center;font-size:16px;padding:10px 0;border-bottom:1px solid #eee}.cf-avatar img{width:35px;height:35px;border-radius:50%;margin-right:12px}.cf-nameblock{display:flex;flex-direction:column;width:180px;margin-right:12px}.cf-name{font-weight:bold;color:#333;font-size:16px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.cf-time{font-size:14px;color:#888;line-height:1.2;margin-top:2px;white-space:nowrap}.cf-status{flex:0 0 auto;margin-right:12px;text-align:left;width:200px}.cf-status span{border-radius:2px;padding:2px 3px;font-size:14px;font-weight:600;white-space:nowrap;display:inline-flex;align-items:center;position:relative;max-width:100%;overflow:hidden;text-overflow:ellipsis;box-sizing:border-box}.cf-status-text{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.cf-status-subtext{position:absolute;top:-2px;right:2px;font-size:10px!important;color:rgba(255,255,255,.8);font-weight:bold;line-height:1;pointer-events:none}.cf-status-accepted{background:rgb(82,196,26);color:#fff}.cf-status-wrong{background:rgb(231,76,60);color:#fff}.cf-status-re{background:rgb(157,61,207);color:#fff}.cf-status-ce{background:rgb(250,219,20);color:#fff}.cf-status-limit{background:rgb(5,34,66);color:#fff}.cf-status-running{background:#888;color:#fff}.cf-status-other{background:rgb(243,156,17);color:#fff}.cf-problem{flex:1;color:rgb(52,152,219);font-size:16px;text-align:left;min-width:100px;margin-left:60px}.cf-error{padding:10px;color:#e74c3c;font-weight:bold}.cf-loading{padding:10px;color:#708090;font-weight:bold}`;document.head.appendChild(style);const getUser = () => {const ne = document.querySelector("#app > div.user-nav.rside.hide.nav-scrollbar > div.title > div > span")|| document.querySelector("#app > div.user-nav.rside.show.nav-scrollbar > div.title > div > span");const ae = document.querySelector("#app > div.top-bar > div.right > div > span.avatar > a > img");return {name: (ne?.textContent || 'User').trim(),color: ne?.style?.color || '#333',avatar: (ae?.src || 'https://cdn.luogu.com.cn/upload/usericon/default.png').trim()};};const fmtVerdict = (v) => STATUS_MAP[v] || [v.split('_').map((w) => w[0] + w.slice(1).toLowerCase()).join(' '),'cf-status-other'];const createCard = (sub) => {const card = document.createElement('div');card.className = 'cf-card';if (sub.id) card.dataset.id = sub.id;const u = getUser();const av = document.createElement('div');av.className = 'cf-avatar';const img = document.createElement('img');img.src = u.avatar;img.onerror = () => img.src = 'https://cdn.luogu.com.cn/upload/usericon/1.png';av.appendChild(img);const nb = document.createElement('div');nb.className = 'cf-nameblock';const nd = document.createElement('div');nd.className = 'cf-name';nd.style.color = u.color;nd.textContent = u.name;const td = document.createElement('div');td.className = 'cf-time';td.textContent = sub.timeText;nb.append(nd, td);const sd = document.createElement('div');sd.className = 'cf-status';const sl = document.createElement('a');sl.href = sub.submitUrl;sl.target = '_blank';sl.rel = 'noopener noreferrer';const sp = document.createElement('span');const [full, cls] = (isCFMode || sub.isFinal) ? fmtVerdict(sub.status) : ['Running', 'cf-status-running'];sp.className = cls;const ts = document.createElement('span');ts.className = 'cf-status-text';ts.textContent = full;sp.appendChild(ts);if (isCFMode && sub.passedTestCount != null && !isNaN(sub.passedTestCount)) {const st = document.createElement('span');st.className = 'cf-status-subtext';st.textContent = String((full === 'AC' || full === 'Accepted')? sub.passedTestCount: sub.passedTestCount + 1);sp.appendChild(st);}sl.appendChild(sp);sd.appendChild(sl);const pd = document.createElement('div');pd.className = 'cf-problem';const pl = document.createElement('a');pl.href = sub.luoguUrl;pl.textContent = sub.taskDisplay;pl.target = '_blank';pl.rel = 'noopener noreferrer';pd.appendChild(pl);card.append(av, nb, sd, pd);return card;};const CACHE_KEY = isCFMode ? CACHE_CF : CACHE_AT;const getLocalCache = () => getCache(CACHE_KEY);const saveLocalCache = (c) => saveCache(CACHE_KEY, c);const updCount = (n) => {const s = document.querySelector('.number');if (s) s.textContent = String(n || 0);};let searchFilter = pid;const render = (cache, mainDiv) => {if (myGen !== pageGen) return;let filtered = cache;if (searchFilter) {const q = isCFMode? searchFilter.toLowerCase(): searchFilter.replace(/^AT_/i, '').toLowerCase();filtered = cache.filter((s) => s.taskDisplay?.toLowerCase().includes(q));}mainDiv.innerHTML = '';updCount(filtered.length);if (!filtered.length) {const msg = document.createElement('div');msg.className = 'cf-loading';msg.textContent = '';mainDiv.appendChild(msg);} else {filtered.forEach((s) => {mainDiv.appendChild(createCard({...s,timeText: new Date(s.timestamp || 0).toLocaleString('zh-CN')}));});}};const bindSearch = async (mainDiv) => {try {const input = await waitForEl('#app > div.main-container.lside-nav > div > main > div > div:nth-child(1) > section:nth-child(1) > div > input:nth-child(1)',8000);if (myGen !== pageGen) return;input.value = searchFilter;const orig = input.oninput;input.oninput = (e) => {searchFilter = e.target.value.trim();const url = new URL(window.location);if (searchFilter) url.searchParams.set('pid', searchFilter);else url.searchParams.delete('pid');history.replaceState(null, '', url);render(getLocalCache(), mainDiv);orig?.call(input, e);};} catch { LOG('未找到搜索框'); }};let mainDiv;try {mainDiv = await waitForEl('#app > div.main-container.lside-nav > div > main > div > div:nth-child(2)',10000);} catch (e) {LOG('记录列表容器未找到', e);return;}if (myGen !== pageGen) return;render(getLocalCache(), mainDiv);await bindSearch(mainDiv);if (myGen !== pageGen) return;if (isCFMode) {if (!disableSync) {let isFetching = false;const updateNow = async () => {if (myGen !== pageGen) return;if (isFetching) return;isFetching = true;try {const handle = GM_getValue('cf-handle', '');if (!handle) return;const sr = await req(`https://codeforces.com/api/user.status?handle=${encodeURIComponent(handle)}&from=1`);if (myGen !== pageGen) return;if (sr.status !== 200) return;const d = JSON.parse(sr.responseText);if (d.status !== 'OK') return;const seen = new Set();const subs = (d.result || []).filter((s) => {if (seen.has(s.id)) return false;seen.add(s.id);return true;}).map((s) => ({id: String(s.id),taskDisplay: `CF${s.contestId}${s.problem.index} - ${s.problem.name}`,status: s.verdict || 'Waiting',timestamp: s.creationTimeSeconds * 1000,submitUrl: `https://www.luogu.com.cn/record/cf/${s.contestId}/${s.id}`,luoguUrl: `https://www.luogu.com.cn/problem/CF${s.contestId}${s.problem.index}`,passedTestCount: s.passedTestCount}));if (myGen !== pageGen) return;saveLocalCache(subs);markUpdated(LAST_UPDATE_CF);render(subs, mainDiv);} catch (e) {LOG('CF 列表更新失败', e.message || e);} finally {isFetching = false;}};updateNow();timers.iv(updateNow, 6000);}} else {let cache = getLocalCache();if (!disableSync) {(async () => {try {const atHandle = GM_getValue('at-handle', '');if (!atHandle) return;const pMap = await fetchATProblems();const kSubs = await fetchATSubmissions(pMap, atHandle);if (myGen !== pageGen) return;const enhanced = kSubs.map((s) => ({ ...s, taskDisplay: fmtATTask(s.taskKey, pMap) }));const mm = new Map();for (const s of [...enhanced, ...cache]) {if (!mm.has(s.id)) mm.set(s.id, s);}cache = Array.from(mm.values()).sort((a, b) => Number(b.id) - Number(a.id));saveLocalCache(cache);markUpdated(LAST_UPDATE_AT);render(cache, mainDiv);} catch (e) {LOG('AT 后台加载失败', e);}})();if (contest) {timers.iv(async () => {if (myGen !== pageGen) return;const prev = getLocalCache();const updated = await crawlATContest(contest, prev);if (myGen !== pageGen) return;if (updated !== prev) {cache = updated;saveLocalCache(cache);markUpdated(LAST_UPDATE_AT);render(cache, mainDiv);}}, 6000);}}}};return { init, destroy };})();// CF/AT 盾提交const ShieldSubmit = (() => {const VALID = [/^https:\/\/www\.luogu\.com\.cn\/problem\/(AT|CF).+/,/^https:\/\/codeforces\.com\/problemset\/status\?my=on$/,/^https:\/\/atcoder\.jp\/contests\/[^/]+\/submit\?RMJ=1$/,/^https:\/\/atcoder\.jp\/contests\/[^/]+\/submissions\/me$/,/^https:\/\/codeforces\.com\/problemset\/submit\/.+/,];const KEYS = ['code', 'contest', 'task', 'back', 'platform', 'pid', 'cf_contest', 'cf_index','body_back', 'bg_image', 'bg_b64', 'bg_color', 'bg_repeat', 'bg_size', 'bg_pos','mid_mask', 'color_filter', 'card_bg', 'card_blur'];const P = 'gen-at-';const set = (k, v) => GM_setValue(P + k, String(v));const get = (k) => GM_getValue(P + k, '');const clr = () => KEYS.forEach((k) => GM_setValue(P + k, ''));const LIMIT = 4e6;const LOGO = 'https://cdn.luogu.com.cn/upload/image_hosting/yy27itbl.png';const setFlag = (k, v) => GM_setValue('rmj-flag-' + k, String(v));const getFlag = (k, def) => GM_getValue('rmj-flag-' + k, def);const clearFlags = () => GM_setValue('rmj-flag-action', '');let submitting = false;let luoguSetupDone = false;let cfAtSetupDone = false;const stripUrl = (v) => {const m = (v || '').match(/url\(\s*(['"]?)(.+?)\1\s*\)/i);return m ? m[2] : v;};const showRedirectMask = () => {if (document.getElementById('rmj-redirect-mask')) return;const m = document.createElement('div');m.id = 'rmj-redirect-mask';m.style.cssText = 'position:fixed!important;inset:0!important;z-index:2147483647!important;background:rgb(239,239,239)!important;pointer-events:all!important;';const attach = () => (document.body || document.documentElement).appendChild(m);if (document.body) attach();else new MutationObserver((_, o) => { if (document.body) { o.disconnect(); attach(); } }).observe(document.documentElement, { childList: true });};GM_addStyle(`.swal2-loader{visibility:hidden}#rmj-overlay{position:fixed!important;inset:0!important;z-index:999998!important;display:flex!important;align-items:center!important;justify-content:center!important;overflow:hidden!important;pointer-events:all!important;cursor:default!important;background:var(--rmj-back,#f5f5f5)!important;color:#333!important;box-sizing:border-box!important;-webkit-font-smoothing:antialiased!important;}#rmj-overlay *{box-sizing:border-box!important;margin:0!important;padding:0!important;font-family:inherit!important;line-height:inherit!important}#rmj-overlay .ly{position:absolute!important;inset:0!important;pointer-events:none!important;-webkit-mask:var(--rmj-mask,none) no-repeat/100% 100%!important;mask:var(--rmj-mask,none) no-repeat/100% 100%!important}#rmj-overlay .ly-c{background:var(--rmj-color,transparent)!important;filter:var(--rmj-filter,none)!important}#rmj-overlay .ly-i{background:var(--rmj-img,none) var(--rmj-pos,center)/var(--rmj-size,cover) var(--rmj-repeat,no-repeat)!important}#rmj-card{position:relative!important;z-index:1!important;width:420px!important;max-width:90vw!important;padding:36px 32px 40px!important;border-radius:4px!important;border:none!important;background:var(--rmj-card,rgba(255,255,255,.78))!important;backdrop-filter:var(--rmj-blur,blur(14px))!important;-webkit-backdrop-filter:var(--rmj-blur,blur(14px))!important;box-shadow:0 8px 32px rgba(0,0,0,.18),0 1.5px 6px rgba(0,0,0,.08)!important;display:flex!important;flex-direction:column!important;align-items:center!important;gap:20px!important;}#rmj-overlay.anim #rmj-card{opacity:0!important;transform:translateY(8px)!important;transition:opacity .45s ease .15s,transform .45s ease .15s!important}#rmj-overlay.anim.open #rmj-card{opacity:1!important;transform:translateY(0)!important}#rmj-card h2{font-size:20px!important;font-weight:600!important;color:#333!important;letter-spacing:.5px!important;user-select:none!important}#rmj-card p{font-size:13px!important;color:#888!important;margin-top:-10px!important;text-align:center!important;user-select:none!important}#rmj-slot{width:100%!important;min-height:78px!important;display:flex!important;align-items:center!important;justify-content:center!important}#rmj-slot:empty::after{content:'等待验证组件加载…';font-size:13px;color:#aaa}#rmj-spin{width:26px;height:26px;border:3px solid rgba(0,0,0,.1);border-top-color:#005c97;border-radius:50%;animation:sp .7s linear infinite}#rmj-error{color:#d32f2f!important;font-size:13px!important;text-align:center!important;word-break:break-all!important;max-height:120px!important;overflow-y:auto!important;padding:8px 12px!important;background:rgba(211,47,47,.08)!important;border-radius:4px!important;width:100%!important;display:none!important}@keyframes sp{to{transform:rotate(360deg)}}body.rmj-lock{overflow:hidden!important;height:100vh!important}`);const toB64 = (raw) => new Promise((res, rej) => {const url = stripUrl(raw);if (!/^https?:\/\//i.test(url || '')) return res('');const img = new Image();img.crossOrigin = 'anonymous';img.onload = () => {try {const cv = document.createElement('canvas');const MAX = 1920;let w = img.naturalWidth, h = img.naturalHeight;if (Math.max(w, h) > MAX) {const s = MAX / Math.max(w, h);w = w * s | 0;h = h * s | 0;}cv.width = w;cv.height = h;cv.getContext('2d').drawImage(img, 0, 0, w, h);let q = 0.9, b = '';while (q >= 0.1) {b = cv.toDataURL('image/jpeg', q);if (b.length <= LIMIT) break;q = +(q - 0.1).toFixed(1);}if (b.length > LIMIT) {const c2 = document.createElement('canvas');c2.width = w >> 1;c2.height = h >> 1;c2.getContext('2d').drawImage(cv, 0, 0, c2.width, c2.height);b = c2.toDataURL('image/jpeg', 0.5);}if (b.length > LIMIT) {const c3 = document.createElement('canvas');c3.width = w >> 2;c3.height = h >> 2;c3.getContext('2d').drawImage(cv, 0, 0, c3.width, c3.height);b = c3.toDataURL('image/jpeg', 0.4);}res(b.length <= LIMIT ? b : '');} catch (e) { rej(e); }};img.onerror = () => rej(new Error('图片加载失败'));img.src = url;});const applyVars = (el) => ThemeStore.applyTo(el);const overlay = (anim, ox, oy) => {document.documentElement.style.overflow = 'hidden';let el = document.getElementById('rmj-overlay');if (el) return el;el = document.createElement('div');el.id = 'rmj-overlay';el.innerHTML = `<div class="ly ly-c"></div><div class="ly ly-i"></div><div id="rmj-card"><h2>正在加载验证</h2><p>通过 Cloudflare 安全验证后将继续提交</p><div id="rmj-error"></div><div id="rmj-slot"><div id="rmj-spin"></div></div></div>`;applyVars(el);const mount = () => {document.body.appendChild(el);if (!anim) return;ox ??= innerWidth / 2;oy ??= innerHeight / 2;const R = Math.hypot(innerWidth, innerHeight) + 60;el.classList.add('anim');el.style.clipPath = `circle(0px at ${ox}px ${oy}px)`;requestAnimationFrame(() => requestAnimationFrame(() => {el.style.transition = 'clip-path .6s cubic-bezier(.22,1,.36,1)';el.style.clipPath = `circle(${R}px at ${ox}px ${oy}px)`;el.classList.add('open');}));};document.body? mount(): new MutationObserver((_, o) => { if (document.body) { o.disconnect(); mount(); } }).observe(document.documentElement, { childList: true });return el;};const showError = (msg) => {const errEl = document.getElementById('rmj-error');const slot = document.getElementById('rmj-slot');const title = document.querySelector('#rmj-card h2');if (errEl) { errEl.textContent = msg; errEl.style.display = 'block'; }if (slot) slot.innerHTML = '';if (title) title.textContent = '操作失败,请检查你的远程 OJ 状态';ERR(msg);};const onBody = (cb) => document.body? cb(): new MutationObserver((_, o) => { if (document.body) { o.disconnect(); cb(); } }).observe(document.documentElement, { childList: true });const setupMeta = (plat) => {document.title = plat === 'codeforces' ? 'GenGen RMJ on CF' : 'GenGen RMJ on AT';const fixIcon = () => {document.querySelectorAll('link[rel*="icon"]').forEach((l) => l.remove());const h = document.head;for (const s of ['16x16', '32x32', '48x48', '192x192']) {const l = document.createElement('link');l.rel = 'icon';l.type = 'image/png';l.href = LOGO;l.sizes = s;h.appendChild(l);}const a = document.createElement('link');a.rel = 'apple-touch-icon';a.href = LOGO;a.sizes = '180x180';h.appendChild(a);};const guard = () => new MutationObserver((muts) => {for (const m of muts) {for (const n of m.addedNodes) {if (n.nodeType === 1 && n.tagName === 'LINK' && /icon/i.test(n.rel) && n.href !== LOGO) {n.remove();fixIcon();return;}}}}).observe(document.head, { childList: true, subtree: true });const noTrans = () => {const h = document.documentElement;h.classList.add('notranslate');h.setAttribute('translate', 'no');h.setAttribute('lang', 'zh-CN');const add = (a) => {const m = document.createElement('meta');Object.entries(a).forEach(([k, v]) => m.setAttribute(k, v));document.head.appendChild(m);};add({ name: 'google', content: 'notranslate' });add({ 'http-equiv': 'Content-Language', content: 'zh-CN' });add({ name: 'msapplication-config', content: 'none' });};const run = () => { fixIcon(); guard(); noTrans(); };document.head? run(): new MutationObserver((_, o) => { if (document.head) { o.disconnect(); run(); } }).observe(document.documentElement, { childList: true, subtree: true });};const SUBMIT_RE = /\/fe\/api\/problem\/submit\/([^/?#]+)/;const setupLuogu = () => {if (luoguSetupDone) return;if (!location.href.includes('luogu.com.cn')) return;luoguSetupDone = true;let click = { x: innerWidth / 2, y: innerHeight / 2 };document.addEventListener('click', (e) => {click = { x: e.clientX, y: e.clientY };}, true);const pidTarget = (raw) => {const p = String(raw).trim();let m = p.match(/^CF(\d+)([A-Z]\d*)$/);if (m) return { plat: 'codeforces', contest: m[1], index: m[2] };m = p.match(/^AT_([a-z0-9]+)_(.+)$/i);if (m) return { plat: 'atcoder', contest: m[1], task: `${m[1]}_${m[2]}` };return null;};const atFromDOM = () => {for (const a of document.querySelectorAll('a[href*="atcoder.jp/contests/"]')) {const m = a.href.match(/atcoder\.jp\/contests\/([^/]+)\/tasks\/([^/?#]+)/);if (m) return { plat: 'atcoder', contest: m[1], task: m[2] };}return null;};const intercept = async (code, pid) => {pid = String(pid).trim();let t = pidTarget(pid);if (!t && /^AT/i.test(pid)) {await new Promise((r) => document.body? r(): new MutationObserver((_, o) => { if (document.body) { o.disconnect(); r(); } }).observe(document.documentElement, { childList: true }));for (let i = 0; i < 30 && !t; i++) {t = atFromDOM();if (!t) await sleep(200);}}if (!t) return;// 未绑定:直接拒绝const bindKey = t.plat === 'codeforces' ? 'cf-handle' : 'at-handle';const bindName = t.plat === 'codeforces' ? 'Codeforces' : 'AtCoder';if (!GM_getValue(bindKey, '')) {overlay(false);showError(`请先在 GenGen RMJ 面板中绑定 ${bindName} 账号`);return;}if (t.plat === 'codeforces' && (!/^\d+$/.test(t.contest) || !/^[A-Z]\d*$/.test(t.index))) {ERR(`CF 目标非法: ${t.contest}/${t.index}`);return;}ThemeStore.extractFromLuogu();set('code', code + `\n\n// 本代码使用 GenGen RMJ 于 ${Date()} 提交 | ${pid}`);set('back', location.href);set('platform', t.plat);set('pid', pid);if (t.plat === 'codeforces') {set('cf_contest', t.contest);set('cf_index', t.index);} else {set('contest', t.contest);set('task', t.task);}// 只在成功时覆盖 bg_b64,避免清空旧数据const bgRaw = get('bg_image');if (bgRaw) {try {const b64 = await toB64(bgRaw);if (b64) set('bg_b64', b64);} catch { /* 保留旧值 */ }}overlay(true, click.x, click.y);const url = t.plat === 'codeforces'? `https://codeforces.com/problemset/submit/${t.contest}/${t.index}?RMJ=1`: `https://atcoder.jp/contests/${t.contest}/submit?RMJ=1`;setTimeout(() => { location.href = url; }, 700);};const XHR = unsafeWindow.XMLHttpRequest;const _open = XHR.prototype.open;const _send = XHR.prototype.send;XHR.prototype.open = function (m, u, ...r) {this._rmj = { m: m.toUpperCase(), u: String(u) };return _open.call(this, m, u, ...r);};XHR.prototype.send = function (body) {const m = this._rmj?.m === 'POST' && SUBMIT_RE.exec(this._rmj.u);if (m) {let code = '';try { code = JSON.parse(String(body ?? '')).code || ''; } catch { /* ignore */ }if (code.trim()) intercept(code, m[1]);this.abort();return;}return _send.call(this, body);};};const setupCfAt = () => {if (cfAtSetupDone) return;cfAtSetupDone = true;const h = location.href;const isFromRMJ = document.referrer.includes('RMJ=1') || getFlag('action');if (h.includes('codeforces.com/problemset/status') && isFromRMJ) {showRedirectMask();handleStatusPage('codeforces');return;}if (h.includes('atcoder.jp/contests/') && h.includes('/submissions/me') && isFromRMJ) {showRedirectMask();handleStatusPage('atcoder');return;}onBody(async () => {if (h.includes('atcoder.jp') && h.includes('RMJ=1')) init('atcoder');else if (h.includes('codeforces.com') && new URL(h).searchParams.get('RMJ') === '1') init('codeforces');});};function init(plat) {setupMeta(plat);document.documentElement.classList.add('rmj-lock');overlay(false);const go = () => submit(plat);document.readyState === 'loading'? document.addEventListener('DOMContentLoaded', go): go();}async function handleStatusPage(plat) {let sid = null;for (let i = 0; i < 10; i++) {sid = await archiveCode(plat);if (sid) break;await sleep(1500);}clearFlags();let targetUrl;if (sid) {if (plat === 'codeforces') {targetUrl = `https://www.luogu.com.cn/record/cf/${get('cf_contest')}/${sid}`;} else {targetUrl = `https://www.luogu.com.cn/record/at/${get('contest')}/${sid}`;}} else {if (plat === 'codeforces') {targetUrl = `https://codeforces.com/contest/${get('cf_contest')}/my`;} else {targetUrl = `https://atcoder.jp/contests/${get('contest')}/submissions/me`;}}location.href = targetUrl;}async function archiveCode(plat) {try {const c = plat === 'codeforces' ? get('cf_contest') : get('contest');if (plat === 'codeforces') {const code = get('code');if (!code) return;const my = `https://codeforces.com/contest/${c}/my`;const doc = new DOMParser().parseFromString(await (await fetch(my, { credentials: 'include' })).text(),'text/html');const sid = (doc.querySelector('a[href*="/submission"]')?.href || '').match(/submissions?\/(\d+)/)?.[1];if (sid) GM_setValue(`{${c},${sid}}`, code);return sid;} else {const res = await fetch(`https://atcoder.jp/contests/${c}/submissions/me/status/json`,{ credentials: 'include' });if (!res.ok) return null;const data = await res.json();if (data && data.Result) {const ids = Object.keys(data.Result);if (ids.length > 0) {ids.sort((a, b) => Number(b) - Number(a));return ids[0];}}return null;}} catch (e) {ERR(e);}}async function submit(plat) {if (submitting) return;submitting = true;try {const code = get('code');if (!code?.trim()) {showError('代码为空,请返回重新操作');clr();return;}document.documentElement.classList.remove('rmj-lock');let form = null;for (let i = 0; i < 100; i++) {form = plat === 'atcoder'? document.querySelector('form[action*="/submit"]'): document.querySelector('form.submitFrameForm')|| document.querySelector('form.submit-form')|| document.querySelector('form[method="post"][action*="csrf_token"]');if (form) break;await sleep(100);}if (!form) {const blocked = /403|just a moment|attention required/i.test(document.title)|| !!document.querySelector('#challenge-stage,#challenge-form,.cf-challenge,iframe[src*="challenges.cloudflare.com"]');if (blocked) {showError('页面被 Cloudflare 拦截,请手动完成验证后刷新');return;}showError('未找到提交表单');clr();return;}if (plat === 'atcoder') {const ta = document.getElementById('plain-textarea');if (ta) { ta.value = code; ta.dispatchEvent(new Event('input', { bubbles: true })); }const ace = document.getElementById('editor') || document.querySelector('.ace_editor');if (ace && unsafeWindow.ace) {try {const e = unsafeWindow.ace.edit(ace);e.setValue(code, 1);e.clearSelection();} catch { /* ignore */ }}} else {const ta = document.querySelector('#sourceCodeTextarea');if (ta) { ta.value = code; ta.dispatchEvent(new Event('input', { bubbles: true })); }const ace = document.getElementById('editor');if (ace && unsafeWindow.ace) {try {const e = unsafeWindow.ace.edit(ace);e.setValue(code, 1);e.clearSelection();} catch { /* ignore */ }}}if (plat === 'atcoder') {const task = get('task');if (task) {const s = document.querySelector('select[name="data.TaskScreenName"]');if (s) { s.value = task; s.dispatchEvent(new Event('change', { bubbles: true })); }}const l = document.querySelector('select[name="data.LanguageId"]');if (l) { l.value = '6017'; l.dispatchEvent(new Event('change', { bubbles: true })); }} else {const l = document.querySelector('select[name="programTypeId"]');if (l) { l.value = '91'; l.dispatchEvent(new Event('change', { bubbles: true })); }}const CF = '.cf-challenge,.cf-turnstile,iframe[src*="challenges.cloudflare.com"],[data-callback*="turnstile"]';let hasCF = false;for (let i = 0; i < 30; i++) {if (document.querySelector(CF)) { hasCF = true; break; }await sleep(100);}let cfToken = '';if (hasCF) {const cfWidget = document.querySelector(CF);const slot = document.getElementById('rmj-slot');if (slot) {const updatePosition = () => {const rect = slot.getBoundingClientRect();const w = 300, h = 65;const top = rect.top + (rect.height - h) / 2;const left = rect.left + (rect.width - w) / 2;cfWidget.style.position = 'fixed';cfWidget.style.top = `${top}px`;cfWidget.style.left = `${left}px`;cfWidget.style.width = `${w}px`;cfWidget.style.height = `${h}px`;cfWidget.style.zIndex = '9999999';cfWidget.style.margin = '0';cfWidget.style.padding = '0';};updatePosition();window.addEventListener('resize', updatePosition);}let tokenFound = false;for (let i = 0; ; i++) {const t = document.querySelector('input[name="turnstileToken"],input[name^="cf-turnstile-response"]');if (t?.value?.length > 10) {cfToken = t.value;tokenFound = true;break;}await sleep(100);}if (!tokenFound) {showError('验证超时,请手动点击提交');return;}}if (plat === 'codeforces' && hasCF) {setFlag('action', 'submit');let submitBtn = form.querySelector('input[type="submit"], button[type="submit"]');if (!submitBtn) submitBtn = form.querySelector('.submit-form-submit, .submit, [name="action"][value="submitSolutionFormSubmitted"]');if (submitBtn) {submitBtn.click();} else {HTMLFormElement.prototype.submit.call(form);}return;}const contest = get('contest');const cfcon = get('cf_contest');let url;if (plat === 'codeforces') {const csrf = form.querySelector('input[name="csrf_token"]')?.value|| document.querySelector('meta[name="csrf_token"]')?.content || '';url = location.origin + location.pathname;if (csrf) url += (url.includes('?') ? '&' : '?') + 'csrf_token=' + encodeURIComponent(csrf);} else {url = form.action || location.href;}const fd = new FormData(form);if (plat === 'codeforces') {fd.set('programTypeId', '91');fd.set('source', code);} else if (plat === 'atcoder') {fd.set('sourceCode', code);}if (cfToken) {fd.set('cf-turnstile-response', cfToken);fd.set('turnstileToken', cfToken);}try {const r = await fetch(url, {method: 'POST',body: fd,credentials: 'include',redirect: 'manual',headers: {Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',Referer: location.href}});const isSuccess = r.type === 'opaqueredirect' || r.status === 302 || r.status === 303 || r.ok;if (!isSuccess) throw new Error(`HTTP ${r.status}`);let sid = null;for (let i = 0; i < 8; i++) {await sleep(1000);sid = await archiveCode(plat);if (sid) break;}clr();if (plat === 'codeforces') {location.href = `https://www.luogu.com.cn/record/cf/${cfcon}/${sid || ''}`;} else if (plat === 'atcoder') {location.href = `https://www.luogu.com.cn/record/at/${contest}/${sid || ''}`;}} catch (e) {showError(`提交失败:\n${e.message}`);clr();}} finally {submitting = false;}}const run = () => {if (!VALID.some((r) => r.test(location.href))) return;setupLuogu();setupCfAt();};return { init: run, showRedirectMask };})();// 主调度const bootstrap = () => {CfChallengePatch.apply();if (isCF()) {MainUI.captureCfHandle();ShieldSubmit.init();return;}if (isLuogu()) {MainUI.init();RecordList.init();RecordDetail.init();ShieldSubmit.init();ThemeStore.extractWithRetry();Router.on(() => {MainUI.hideModal();MainUI.handleRoute();RecordList.init();RecordDetail.init();ShieldSubmit.init();});return;}if (isAT()) {ShieldSubmit.init();return;}if (isCfChallenge()) return;};docReady(bootstrap);})();```:::**表情包**收藏:::info```// ==UserScript==// @name 洛谷图片收藏// @namespace https://www.luogu.com.cn/// @version 2.0.0// @description 收藏图片网址,点击即可插入 Markdown,支持预览开关// @author xcb & ChatGPT// @match https://www.luogu.com.cn/*// @match https://*.luogu.com.cn/*// @match https://*.luogu.com/*// @grant none// @run-at document-idle// ==/UserScript==(() => {'use strict';const STORAGE_KEY = 'lg_saved_images_v1';const PREVIEW_KEY = 'lg_image_preview_enabled';const PANEL_ID = 'lg-image-collection-root';// ==================== 数据管理 ====================function loadImages() {try {const data = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]');return Array.isArray(data) ? data : [];} catch {return [];}}function saveImages() {localStorage.setItem(STORAGE_KEY, JSON.stringify(images));}let images = loadImages();// 默认关闭图片预览let previewEnabled = localStorage.getItem(PREVIEW_KEY) === 'true';// ==================== 编辑器光标记忆 ====================let lastEditor = null;let lastSelectionStart = 0;let lastSelectionEnd = 0;function isEditor(element) {if (!element || element.nodeType !== 1) return false;if (element.matches('textarea, input')) {return !element.disabled && !element.readOnly;}return element.isContentEditable;}function rememberCursor(element) {if (!isEditor(element)) return;lastEditor = element;if (element instanceof HTMLTextAreaElement ||element instanceof HTMLInputElement) {lastSelectionStart = element.selectionStart ?? element.value.length;lastSelectionEnd = element.selectionEnd ?? element.value.length;}}document.addEventListener('focusin', event => {if (isEditor(event.target)) {rememberCursor(event.target);}}, true);document.addEventListener('keyup', event => {if (isEditor(event.target)) {rememberCursor(event.target);}}, true);document.addEventListener('click', event => {if (isEditor(event.target)) {rememberCursor(event.target);}}, true);document.addEventListener('input', event => {if (isEditor(event.target)) {rememberCursor(event.target);}}, true);// ==================== Markdown 插入 ====================function insertText(text) {let editor = lastEditor;// 如果当前焦点仍在编辑器中,优先使用当前编辑器if (isEditor(document.activeElement)) {editor = document.activeElement;}if (!editor || !editor.isConnected) {alert('没有找到编辑器,请先点击洛谷的编辑框。');return;}// textarea / inputif (editor instanceof HTMLTextAreaElement ||editor instanceof HTMLInputElement) {const start = Math.min(lastSelectionStart,editor.value.length);const end = Math.min(lastSelectionEnd,editor.value.length);editor.focus();editor.setRangeText(text, start, end, 'end');lastSelectionStart = editor.selectionStart;lastSelectionEnd = editor.selectionEnd;editor.dispatchEvent(new Event('input', {bubbles: true}));return;}// contenteditableif (editor.isContentEditable) {editor.focus();const selection = window.getSelection();if (selection && selection.rangeCount) {const range = selection.getRangeAt(0);if (editor.contains(range.commonAncestorContainer)) {range.deleteContents();const node = document.createTextNode(text);range.insertNode(node);range.setStartAfter(node);range.collapse(true);selection.removeAllRanges();selection.addRange(range);editor.dispatchEvent(new InputEvent('input', {bubbles: true,inputType: 'insertText',data: text}));return;}}document.execCommand('insertText', false, text);return;}alert('暂不支持当前编辑器。');}// ==================== 创建 UI ====================if (document.getElementById(PANEL_ID)) return;const root = document.createElement('div');root.id = PANEL_ID;document.body.appendChild(root);const shadow = root.attachShadow({mode: 'open'});shadow.innerHTML = `<style>* {box-sizing: border-box;}:host {color-scheme: light dark;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;}.launcher {position: fixed;right: 22px;bottom: 24px;z-index: 999999;width: 48px;height: 48px;border: none;border-radius: 50%;background: #18a058;color: white;font-size: 22px;cursor: pointer;box-shadow: 0 3px 12px #0003;transition: transform .15s, background .15s;}.launcher:hover {background: #36ad6a;transform: scale(1.08);}.panel {position: fixed;right: 22px;bottom: 84px;z-index: 999999;width: 360px;max-width: calc(100vw - 32px);max-height: min(620px, calc(100vh - 120px));display: none;flex-direction: column;overflow: hidden;border: 1px solid var(--border);border-radius: 12px;background: var(--bg);color: var(--fg);box-shadow: 0 5px 24px #0003;}.panel.open {display: flex;}.header {display: flex;align-items: center;justify-content: space-between;padding: 14px 16px;border-bottom: 1px solid var(--border);font-size: 16px;font-weight: 700;}.close {border: none;background: transparent;color: var(--muted);font-size: 22px;cursor: pointer;}.toolbar {padding: 12px;border-bottom: 1px solid var(--border);}input {width: 100%;min-width: 0;padding: 9px 10px;border: 1px solid var(--border);border-radius: 7px;outline: none;background: var(--input);color: var(--fg);font-size: 13px;}input:focus {border-color: #18a058;}button {font-family: inherit;}.add-row {display: flex;gap: 8px;margin-top: 8px;}.add-row input {flex: 1;}.btn {padding: 8px 12px;border: none;border-radius: 7px;background: #18a058;color: white;cursor: pointer;white-space: nowrap;}.btn:hover {background: #36ad6a;}.preview-row {display: flex;align-items: center;justify-content: space-between;gap: 10px;margin-top: 10px;font-size: 13px;}.switch {display: flex;align-items: center;gap: 7px;cursor: pointer;user-select: none;}.switch input {width: 16px;height: 16px;accent-color: #18a058;cursor: pointer;}.hint {color: var(--muted);font-size: 11px;}.search {margin-top: 10px;}.list {flex: 1;min-height: 80px;overflow-y: auto;padding: 10px;}.item {display: flex;gap: 10px;align-items: center;padding: 9px;margin-bottom: 8px;border: 1px solid var(--border);border-radius: 8px;cursor: pointer;transition: background .15s;}.item:hover {background: var(--hover);}.preview {width: 64px;height: 64px;flex-shrink: 0;display: flex;align-items: center;justify-content: center;overflow: hidden;border-radius: 6px;background: var(--hover);color: var(--muted);font-size: 11px;text-align: center;}.preview img {width: 100%;height: 100%;object-fit: contain;}.info {flex: 1;min-width: 0;}.url {overflow: hidden;display: -webkit-box;-webkit-box-orient: vertical;-webkit-line-clamp: 3;word-break: break-all;font-size: 12px;line-height: 1.5;}.item-actions {display: flex;flex-direction: column;gap: 5px;}.delete {padding: 5px 8px;border: none;border-radius: 5px;background: #d03050;color: white;font-size: 11px;cursor: pointer;}.empty {padding: 35px 10px;color: var(--muted);text-align: center;font-size: 13px;}.footer {padding: 9px 12px;border-top: 1px solid var(--border);color: var(--muted);font-size: 11px;text-align: center;}@media (prefers-color-scheme: dark) {.panel {--bg: #202127;--fg: #e5e5e5;--muted: #999;--border: #41434b;--input: #303139;--hover: #303139;}}@media (prefers-color-scheme: light) {.panel {--bg: #fff;--fg: #222;--muted: #888;--border: #e5e5e5;--input: #fafafa;--hover: #f5f5f5;}}.panel.dark {--bg: #202127;--fg: #e5e5e5;--muted: #999;--border: #41434b;--input: #303139;--hover: #303139;}.panel.light {--bg: #fff;--fg: #222;--muted: #888;--border: #e5e5e5;--input: #fafafa;--hover: #f5f5f5;}</style><button class="launcher" title="图片收藏">🧊</button><div class="panel"><div class="header"><span>图片收藏</span><button class="close" title="关闭">×</button></div><div class="toolbar"><div class="add-row"><inputclass="url-input"type="text"placeholder="输入图片网址..."><button class="btn add-btn">添加</button></div><div class="preview-row"><label class="switch"><input class="preview-checkbox" type="checkbox"><span>开启图片预览</span></label><span class="hint">默认关闭,不加载图片</span></div><inputclass="search"type="text"placeholder="搜索图片网址..."></div><div class="list"></div><div class="footer">点击条目插入 Markdown 图片语法</div></div>`;const $ = selector => shadow.querySelector(selector);const launcher = $('.launcher');const panel = $('.panel');const closeButton = $('.close');const urlInput = $('.url-input');const addButton = $('.add-btn');const searchInput = $('.search');const list = $('.list');const previewCheckbox = $('.preview-checkbox');// ==================== 面板开关 ====================launcher.addEventListener('click', () => {panel.classList.toggle('open');if (panel.classList.contains('open')) {renderImages();}});closeButton.addEventListener('click', () => {panel.classList.remove('open');});// ==================== 图片预览开关 ====================function updatePreview() {previewCheckbox.checked = previewEnabled;localStorage.setItem(PREVIEW_KEY,String(previewEnabled));renderImages();}previewCheckbox.checked = previewEnabled;previewCheckbox.addEventListener('change', () => {previewEnabled = previewCheckbox.checked;updatePreview();});// ==================== 添加图片 ====================function addImage() {const url = urlInput.value.trim();if (!url) {alert('请输入图片网址。');return;}let parsed;try {parsed = new URL(url);} catch {alert('图片网址格式不正确。');return;}if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {alert('只支持 HTTP 和 HTTPS 图片网址。');return;}if (images.some(item => item.url === url)) {alert('这张图片已经收藏过了。');return;}images.unshift({id: Date.now() + Math.random().toString(16).slice(2),url});saveImages();urlInput.value = '';searchInput.value = '';renderImages();}addButton.addEventListener('click', addImage);urlInput.addEventListener('keydown', event => {if (event.key === 'Enter') {addImage();}});// ==================== 删除图片 ====================function deleteImage(id) {images = images.filter(item => item.id !== id);saveImages();renderImages();}// ==================== 渲染图片列表 ====================function renderImages() {list.replaceChildren();const keyword = searchInput.value.trim().toLowerCase();const filtered = images.filter(item =>item.url.toLowerCase().includes(keyword));if (!filtered.length) {const empty = document.createElement('div');empty.className = 'empty';empty.textContent = images.length? '没有找到匹配的图片。': '还没有收藏图片,先添加一个吧。';list.appendChild(empty);return;}for (const item of filtered) {const row = document.createElement('div');row.className = 'item';const preview = document.createElement('div');preview.className = 'preview';if (previewEnabled) {const img = document.createElement('img');img.alt = '图片预览';img.loading = 'lazy';img.referrerPolicy = 'no-referrer';// 只有开启预览时才设置 srcimg.src = item.url;img.onerror = () => {preview.textContent = '加载失败';};preview.appendChild(img);} else {preview.textContent = '预览关闭';}const info = document.createElement('div');info.className = 'info';const url = document.createElement('div');url.className = 'url';url.textContent = item.url;info.appendChild(url);const actions = document.createElement('div');actions.className = 'item-actions';const del = document.createElement('button');del.className = 'delete';del.textContent = '删除';del.addEventListener('click', event => {event.stopPropagation();if (confirm('确定删除这张图片吗?')) {deleteImage(item.id);}});actions.appendChild(del);row.appendChild(preview);row.appendChild(info);row.appendChild(actions);// 点击条目插入 Markdownrow.addEventListener('click', () => {insertText(``);});list.appendChild(row);}}searchInput.addEventListener('input', renderImages);// ==================== 暗色模式 ====================function updateTheme() {const dark = document.documentElement.classList.contains('dark')|| document.body.classList.contains('dark')|| document.documentElement.dataset.theme === 'dark';panel.classList.toggle('dark', dark);panel.classList.toggle('light', !dark);}updateTheme();const observer = new MutationObserver(updateTheme);observer.observe(document.documentElement, {attributes: true,attributeFilter: ['class', 'data-theme']});observer.observe(document.body, {attributes: true,attributeFilter: ['class']});// ==================== 初始化 ====================renderImages();})();```:::