正文
增加 64 行删除 382 行
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409注:本脚本**仅**使用 `AI` 生成。使用如下插件:```// ==UserScript==// @name VJudge 提交同步助手// @namespace http://tampermonkey.net/// @version 1.3// @description 自动获取 AtCoder/Codeforces/Luogu 的做题记录并同步到 VJudge,根据提交次数智能跳过和补交// @author You// @match https://*.vjudge.net/*// @grant GM_setValue// @grant GM_getValue// @grant GM_xmlhttpRequest// @grant GM_notification// @grant GM_registerMenuCommand// @connect kenkoooo.com// @connect codeforces.com// ==/UserScript==(function() {'use strict';// ==================== 样式与 UI ====================const fabHTML = `<div id="vj-sync-fab" style="position: fixed; right: 20px; bottom: 20px; width: 50px; height: 50px; background: #4CAF50; color: white; border-radius: 50%; display: flex; justify-content: center; align-items: center; cursor: pointer; box-shadow: 0 4px 8px rgba(0,0,0,0.3); z-index: 99998; font-size: 24px; font-weight: bold; transition: transform 0.2s;">V</div>`;document.body.insertAdjacentHTML('beforeend', fabHTML);const panelHTML = `<div id="vj-sync-panel" style="position: fixed; top: 10px; right: 10px; width: 360px; background: #fff; border: 1px solid #ccc; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.15); z-index: 99999; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; display: none;"><div id="vj-sync-header" style="padding: 10px; background: #4CAF50; color: white; border-radius: 8px 8px 0 0; cursor: move; display: flex; justify-content: space-between; align-items: center;"><strong>VJudge 同步助手</strong><button id="vj-sync-close" style="background: none; border: none; color: white; font-size: 16px; cursor: pointer;">×</button></div><div style="padding: 15px;"><div style="margin-bottom: 10px; background: #e8f5e9; padding: 8px; border-radius: 4px; border: 1px solid #c8e6c9;"><label style="display:block; font-size:13px; color:#2e7d32; font-weight:bold;">VJudge 用户名 (必填):</label><input type="text" id="vj-username" placeholder="用于查询已有提交记录以跳过" style="width: 100%; padding: 5px; border: 1px solid #a5d6a7; border-radius: 4px; margin-top:4px;"></div><div style="margin-bottom: 10px;"><label style="display:block; font-size:12px; color:#666;">AtCoder 用户名:</label><input type="text" id="vj-atc-user" style="width: 100%; padding: 5px; border: 1px solid #ddd; border-radius: 4px;"></div><div style="margin-bottom: 10px;"><label style="display:block; font-size:12px; color:#666;">Codeforces 用户名:</label><input type="text" id="vj-cf-user" style="width: 100%; padding: 5px; border: 1px solid #ddd; border-radius: 4px;"></div><div style="margin-bottom: 10px;"><label style="display:block; font-size:12px; color:#666;">洛谷题目ID (逗号分隔, 可选):</label><input type="text" id="vj-lg-probs" placeholder="P1001,P1002" style="width: 100%; padding: 5px; border: 1px solid #ddd; border-radius: 4px;"></div><button id="vj-sync-start" style="width: 100%; padding: 8px; background: #4CAF50; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 14px;">开始同步</button><div id="vj-sync-log" style="margin-top: 10px; height: 220px; overflow-y: auto; background: #f9f9f9; padding: 8px; border-radius: 4px; font-size: 12px; border: 1px solid #eee; line-height: 1.5;"></div></div></div>`;document.body.insertAdjacentHTML('beforeend', panelHTML);const panel = document.getElementById('vj-sync-panel');const header = document.getElementById('vj-sync-header');let isDragging = false, offsetX, offsetY;header.onmousedown = (e) => { isDragging = true; offsetX = e.clientX - panel.offsetLeft; offsetY = e.clientY - panel.offsetTop; };document.onmousemove = (e) => { if (isDragging) { panel.style.left = (e.clientX - offsetX) + 'px'; panel.style.top = (e.clientY - offsetY) + 'px'; } };document.onmouseup = () => { isDragging = false; };const closeBtn = document.getElementById('vj-sync-close');const fabBtn = document.getElementById('vj-sync-fab');const openPanel = () => { panel.style.display = 'block'; loadSettings(); };const closePanel = () => { panel.style.display = 'none'; };closeBtn.onclick = () => { closePanel(); };fabBtn.onclick = () => { openPanel(); };fabBtn.onmouseenter = () => { fabBtn.style.transform = 'scale(1.1)'; };fabBtn.onmouseleave = () => { fabBtn.style.transform = 'scale(1)'; };GM_registerMenuCommand('打开 VJudge 同步面板', () => { openPanel(); });const logArea = document.getElementById('vj-sync-log');function log(msg, type = 'info') {const colors = { info: '#333', success: '#4CAF50', error: '#f44336', warning: '#ff9800' };logArea.innerHTML += `<div style="color: ${colors[type]}">${new Date().toLocaleTimeString()} - ${msg}</div>`;logArea.scrollTop = logArea.scrollHeight;}function loadSettings() {document.getElementById('vj-username').value = GM_getValue('vj_username', '');document.getElementById('vj-atc-user').value = GM_getValue('atc_user', '');document.getElementById('vj-cf-user').value = GM_getValue('cf_user', '');document.getElementById('vj-lg-probs').value = GM_getValue('lg_probs', '');}function saveSettings() {GM_setValue('vj_username', document.getElementById('vj-username').value.trim());GM_setValue('atc_user', document.getElementById('vj-atc-user').value.trim());GM_setValue('cf_user', document.getElementById('vj-cf-user').value.trim());GM_setValue('lg_probs', document.getElementById('vj-lg-probs').value.trim());}// ==================== 核心逻辑 ====================const OJ_CONFIG = {atcoder: { language: "5001", oj: "AtCoder", vjOjId: "AtCoder" },codeforces: { language: "91", oj: "CodeForces", vjOjId: "CodeForces" },luogu: { language: "27", oj: "洛谷", vjOjId: "%E6%B4%9B%E8%B0%B7" }};const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));function gmGet(url) {return new Promise((resolve, reject) => {GM_xmlhttpRequest({method: "GET",url: url,responseType: "json",onload: res => resolve(res.response),onerror: err => reject(err)});});}// ★★★ 修改:获取 VJudge 上的所有提交记录并统计每题次数 ★★★async function fetchVJSubmissions(vjUsername, ojName) {const vjOjId = OJ_CONFIG[ojName].vjOjId;let probCounts = new Map(); // 记录每个题目的提交次数let start = 0;const length = 20;log(`正在获取 VJudge 上 ${OJ_CONFIG[ojName].oj} 的提交记录...`);while (true) {// 删去了 res=AC 参数,获取全部提交记录const url = `https://vjudge.net/status/data?start=${start}&length=${length}&un=${encodeURIComponent(vjUsername)}&OJId=${vjOjId}&probNum=`;try {const res = await fetch(url);if (!res.ok) {log(`❗ 获取 VJudge 提交记录失败: ${res.status}`, 'error');break;}const data = await res.json();if (!data.data || data.data.length === 0) {break;}data.data.forEach(item => {if (item.probNum) {const p = item.probNum.trim().toUpperCase();probCounts.set(p, (probCounts.get(p) || 0) + 1);}});start += length;await sleep(200);} catch (e) {log(`❗ 获取 VJudge 提交记录异常: ${e.message}`, 'error');break;}}log(`✅ 在 VJudge 上发现 ${probCounts.size} 道 ${OJ_CONFIG[ojName].oj} 的题目有提交记录`, 'info');return probCounts;}// ★★★ 修改:返回 Map,记录每道题的提交次数 ★★★async function getATCProblems(user) {log(`获取 AtCoder 题目信息...`);const url = "https://kenkoooo.com/atcoder/atcoder-api/v3/user/submissions";let submissions = GM_getValue('atc_submissions', []);let lastTime = submissions.length > 0 ? submissions[submissions.length - 1].epoch_second + 1 : 0;while (true) {const data = await gmGet(`${url}?user=${user}&from_second=${lastTime}`);if (!data || data.length === 0) break;submissions.push(...data);lastTime = data[data.length - 1].epoch_second + 1;await sleep(1000);}GM_setValue('atc_submissions', submissions);let probCounts = new Map();submissions.forEach(item => {let p = item.problem_id.trim().toUpperCase();probCounts.set(p, (probCounts.get(p) || 0) + 1);});log(`获取 AtCoder 题目成功, 共 ${probCounts.size} 道题目`, 'success');return probCounts;}// ★★★ 修改:返回 Map,记录每道题的提交次数 ★★★async function getCFProblems(user) {log(`获取 Codeforces 题目信息...`);const url = `https://codeforces.com/api/user.status?handle=${user}`;const response = await gmGet(url);if (response.status !== 'OK') {log(`获取 Codeforces 题目失败: ${response.comment}`, 'error');return new Map();}let probCounts = new Map();response.result.forEach(item => {let p = (String(item.problem.contestId) + item.problem.index).trim().toUpperCase();probCounts.set(p, (probCounts.get(p) || 0) + 1);});log(`获取 Codeforces 题目成功, 共 ${probCounts.size} 道题目`, 'success');return probCounts;}// ★★★ 修改:比对提交次数,若 VJudge 次数不足则补交 ★★★async function submitToVJ(ojName, ojProbCounts, vjUsername) {let vjProbCounts = new Map();if (vjUsername) {vjProbCounts = await fetchVJSubmissions(vjUsername, ojName);} else {log('⚠️ 未填写 VJudge 用户名,无法比对提交记录,将尝试提交所有题目', 'warning');}log(`开始提交 ${OJ_CONFIG[ojName].oj} 做题信息,待检查 ${ojProbCounts.size} 题`);let succ = GM_getValue('success_problems', {});let skipCount = 0;let submitCount = 0;for (let [probNum, ojCount] of ojProbCounts.entries()) {let vjCount = vjProbCounts.get(probNum) || 0;// 计算需要补交的次数let needSubmitTimes = ojCount - vjCount;if (needSubmitTimes <= 0) {skipCount++;continue;}submitCount++;let data = new URLSearchParams();data.append("method", "2");data.append("language", OJ_CONFIG[ojName].language);data.append("open", "1");data.append("source", "");let ojNamePost = OJ_CONFIG[ojName].oj;if (ojName === "codeforces" && probNum.length > 6) ojNamePost = "Gym";data.append("oj", ojNamePost);data.append("probNum", probNum);try {const res = await fetch(`https://vjudge.net/problem/submit/${ojNamePost}-${probNum}`, {method: 'POST',headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8','X-Requested-With': 'XMLHttpRequest'},body: data.toString()});if (!res.ok) {if (res.status === 401 || res.status === 403) {log(`❗ 请求被拒绝 (${res.status}),请确保您已在 VJudge 登录!`, 'error');return;}continue;}const result = await res.json();succ[probNum] = result;GM_setValue('success_problems', succ);if (result.success || result.error === "No recent submissions found") {log(`✅ 更新 ${ojNamePost}-${probNum} 成功`, 'success');} else if (result.i18nKey === 'submit.error.login_required' || (typeof result.error === 'object' && result.error.i18nKey === 'submit.error.login_required')) {log(`❗ 未登录,请先在浏览器登录 VJudge!`, 'error');return;} else {let errorMsg = result.error;if (typeof errorMsg === 'object') {errorMsg = JSON.stringify(errorMsg);}log(`❌ 更新 ${ojNamePost}-${probNum} 失败: ${errorMsg}`, 'warning');}} catch (e) {log(`❗ 网络请求异常: ${e.message}`, 'error');}// 随机延迟 3~8 秒await sleep(Math.floor(Math.random() * 5000) + 3000);}if (skipCount > 0) {log(`⏩ 已跳过 ${skipCount} 道在 VJudge 上提交次数已对齐的题目`, 'info');}if (submitCount === 0 && skipCount > 0) {log(`🎉 ${OJ_CONFIG[ojName].oj} 所有题目提交次数均已对齐,无需提交`, 'success');}}// 主流程document.getElementById('vj-sync-start').onclick = async function() {const vjUsername = document.getElementById('vj-username').value.trim();const atcUser = document.getElementById('vj-atc-user').value.trim();const cfUser = document.getElementById('vj-cf-user').value.trim();const lgProbsStr = document.getElementById('vj-lg-probs').value.trim();if (!atcUser && !cfUser && !lgProbsStr) {log('❗ 请至少填写一个平台的用户名或题目!', 'error');return;}this.disabled = true;this.innerText = '同步中...';logArea.innerHTML = '';saveSettings();try {if (atcUser) {const atcProbCounts = await getATCProblems(atcUser);await submitToVJ('atcoder', atcProbCounts, vjUsername);}if (cfUser) {const cfProbCounts = await getCFProblems(cfUser);await submitToVJ('codeforces', cfProbCounts, vjUsername);}if (lgProbsStr) {let lgProbCounts = new Map();// 洛谷由于只能手动输入题目ID,默认视作原站提交1次lgProbsStr.split(',').map(p => p.trim().toUpperCase()).filter(p => p).forEach(p => {lgProbCounts.set(p, 1);});await submitToVJ('luogu', lgProbCounts, vjUsername);}log('🎉🎉🎉 所有同步任务完成!', 'success');GM_notification({ text: 'VJudge 同步完成!', title: '提示' });} catch (e) {log(`发生致命错误: ${e.message}`, 'error');} finally {this.disabled = false;this.innerText = '开始同步';}};})();```其中,爬取洛谷可以使用如下代码,使用方式为直接复制主页的所有信息即可:```cpp#include <iostream>#include <string>#include <sstream>#include <vector>#include <cctype>bool is_luogu_id(const std::string& s) {if (s.empty()) return false;// 第一个字符必须是大写字母if (!isupper(s[0])) return false;// 必须至少包含一个数字bool has_digit = false;for (char c : s) {if (isdigit(c)) {has_digit = true;break;}}if (!has_digit) return false;// 允许的字符:字母、数字、下划线for (char c : s) {if (!(isalnum(c) || c == '_')) return false;}return true;}int main() {std::string line;std::vector<std::string> ids;while (std::getline(std::cin, line)) {std::istringstream iss(line);std::string token;while (iss >> token) {if (is_luogu_id(token)) {ids.push_back(token);}}}// 输出,逗号分隔for (size_t i = 0; i < ids.size(); ++i) {if (i > 0) std::cout << ',';std::cout << ids[i];}std::cout << std::endl;return 0;}```本文仅做分享使用。欢迎报告错误 /kel12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091本脚本由 AI 基于 <https://github.com/xiaowhang/vjudge-submission-tracker> 修改。获取通过题目的部分是人类写的。## 辅助工具用来获取 OJ 的通过题目列表。获取 QOJ 已通过题目列表:```javascriptconsole.log($(".list-group-item-text").eq(6).children().map(function() {return $(this).text();}).get().join(','));```获取 UOJ 已通过题目列表:```javascriptconsole.log($(".uoj-ac-problems-list").children().children().map(function(){return $(this).text().match(/#([^.]*)\./)[1];}).get().join(','));```获取洛谷已通过题目列表:```javascriptacceptedProblems = [];const targetProblems = Array.from(document.querySelectorAll(".problems")).slice(1, 10).forEach(problems => {problems.querySelectorAll("a").forEach(link => {acceptedProblems.push(link.textContent.trim());})});console.log(acceptedProblems);acceptedProblems = acceptedProblems.filter(problem => {return !/^(AT|CF|UVA|SP)/.test(problem);});console.log(acceptedProblems.join(','));```上面的指令使用方法是:到对应 OJ 的个人主页里面,按 F12 打开浏览器的控制台,随后将指令输入即可得到对应 OJ 中所有你通过的题目编号。特别的,洛谷的要在个人练习页面中使用,原因是指令原理是爬取当前页面上的元素。对于 CF 和 AT 脚本使用了对应的 API,无须手动获取。## 插件下面是插件,使用方法为放置到 tampermonkey 内。刷新 Vjudge 页面后会发现右下角有一个绿色的大 V 按钮,点击后输入信息即可使用。对于 CF 和 AT,更新逻辑为原 OJ 提交次数不等于 Vjudge 提交次数,就更新。对于洛谷,QOJ 和 UOJ,仅更新列出的在 Vjudge 上未通过的题目。[插件源代码](https://www.luogu.com.cn/article/o3u4m0g7)有 bug 可以私信反馈。注意极小部分题目是 Vjudge 上没有或者定向错误的,需要手动操作。/kel---## 补丁:获取五个 OJ 的 bindingId 教程### 通用步骤1. 在 VJudge 打开对应 OJ 的任意题目页面(如 AtCoder、Codeforces、洛谷、QOJ、UOJ)。2. 按 `F12` 打开开发者工具,切换到 **Network(网络)** 标签,勾选 **Preserve log**,点击 **Fetch/XHR** 过滤。3. 在题目页面点击 **归档** 或 **标记为已解决** 按钮(若找不到,可提交一次空代码:`method=2` 且 `source` 留空)。4. 在 Network 面板中找到请求,URL 类似 `/problem/submit/XXX`。5. 点击该请求,右侧选择 **Payload** 或 **Form Data** 标签,找到 `bindingId` 字段,复制其值。6. 将该值填入脚本面板中对应 OJ 的绑定账号 ID 输入框。### 各 OJ 名称对应关系| OJ | 脚本面板中的输入框 ||------------|-------------------|| AtCoder | AtCoder 绑定 ID || Codeforces | Codeforces 绑定 ID || 洛谷 | 洛谷 绑定 ID || QOJ | QOJ 绑定 ID || UOJ | UOJ 绑定 ID |> 如果找不到归档按钮,可以在题目页面用空代码提交一次,抓取提交请求中的 `bindingId`。如果看不懂欢迎私信交流。### 后补在 https://vjudge.net/user/remoteAccounts/list?oj=%E6%B4%9B%E8%B0%B7 的页面就能看到这个 bindingId,具体来说,会有一个 "id":xxxxxx 的字段,将其读出来就可以了。对应的,https://vjudge.net/user/remoteAccounts/list?oj= 后面可以填别的 OJ 的名字,例如 CodeForces,AtCoder,QOJ,UniversalOJ。## 补补丁傻逼 QOJ 上了 codeflare,导致一次只能爬取三个提交记录。请反复批量归档。这个我修不好了。