trick
回文括号序列
记 ( 为 ,) 为 。
记 表示前 个括号的和,有:
- 每个 。
- 。
等差数列
- 首先
- 其次相邻两数差的绝对值的是
- 区间内的数不重复
对于二进制数 ,求同样 的个数的下个数
int solve(int x){return ((((x + (x & -x)) ^ x) >> 2) / (x & -x)) | (x + (x & -x));}插件
copy_markdown
// ==UserScript==
// @name copy-markdown
// @namespace https://github.com/LYkcul
// @description 获取页面 Markdown 源代码
// @author BlackPanda
// @license MIT
// @version 1.2.0
// @match https://www.luogu.com.cn/*
// @match https://www.luogu.com/*
// @grant none
// ==/UserScript==
(function () {
"use strict";
function injectStyle() {
var style = document.createElement("style");
style.textContent = `
.lcolor-var-green-3 {
--lcolor-rgb: 82, 196, 26;
}
.lcolor-var-blue-3 {
--lcolor-rgb: 52, 152, 219;
}
.lcolor-var-red-3 {
--lcolor-rgb: 231, 76, 60;
}
.copy-markdown-btn {
--l-button--real-color: var(--lcolor-rgb, var(--lcolor--primary, var(--lcolor--primary, 52, 152, 219)));
display: inline-block;
outline: none;
cursor: pointer;
font-weight: inherit;
line-height: 1.5;
text-align: center;
vertical-align: middle;
border-radius: 3px;
border: 1px solid rgb(var(--l-button--real-color));
background: rgba(var(--l-button--real-color),0) none;
color: rgb(var(--l-button--real-color));
margin-right: .5em;
}
.copy-markdown-btn-contest {
--l-button--real-color: var(--lcolor-rgb, var(--lcolor--primary, var(--lcolor--primary, 52, 152, 219)));
display: inline-block;
outline: none;
cursor: pointer;
font-weight: inherit;
line-height: 1.5;
text-align: center;
vertical-align: middle;
border-radius: 3px;
border: 1px solid rgb(var(--l-button--real-color));
background: rgb(var(--l-button--real-color));
color: #fff;
margin-right: .5em;
}
/* why no margin-right on exlg-cph??? */
.exlg-cph + .copy-markdown-btn-contest {
margin-left: .5em;
}
`;
document.head.appendChild(style);
}
/*====================*/
const routes = [
{
name: "article_show",
match: (path) => /^\/(article)\/(?!mine$|_?new$)[A-Za-z0-9]+$/.test(path),
mount: ".user-nav",
getContent: async () => {
let ele = document.querySelector("script#lentille-context");
let json = JSON.parse(ele.textContent.trim());
let url = location.href;
if (url.endsWith("/")) url = url.slice(0, -1);
if (
json.template !== "article.show" ||
json.data.article.lid !== url.split("/").pop()
) {
console.log("[DEBUG] retry");
const res = await fetch(location.href, {
credentials: "include",
headers: {
"x-requested-with": "XMLHttpRequest",
"x-lentille-request": "content-only",
},
});
const html = await res.text();
json = JSON.parse(html.trim());
}
console.log(json);
const content = json.data?.article?.content || "复制失败";
return content;
},
},
{
name: "user_detail",
match: (path) => /^\/user\/\d+$/.test(path),
test: (url) => !(url.hash && url.hash.length > 1 && url.hash !== "#main"),
mount: ".user-nav",
getContent: async () => {
return _feInstance.currentData.user.introduction || "复制失败";
},
className: "lfe-form-sz-middle lcolor-var-blue-3 copy-markdown-btn",
classNameSucc: "lfe-form-sz-middle lcolor-var-green-3 copy-markdown-btn",
classNameErr: "lfe-form-sz-middle lcolor-var-red-3 copy-markdown-btn",
},
{
name: "contest_detail",
match: (path) => /^\/contest\/\d+$/.test(path),
test: (url) =>
!(url.hash && url.hash.length > 1 && url.hash !== "#description"),
mount: ".functional > .operation",
specialMount: true,
getContent: async () => {
return _feInstance.currentData.contest.description || "复制失败";
},
className:
"lfe-form-sz-middle lcolor-var-blue-3 copy-markdown-btn-contest",
classNameSucc:
"lfe-form-sz-middle lcolor-var-green-3 copy-markdown-btn-contest",
classNameErr:
"lfe-form-sz-middle lcolor-var-red-3 copy-markdown-btn-contest",
selfMount: ".copy-markdown-btn-contest",
},
{
name: "training_detail",
match: (path) => /^\/training\/\d+$/.test(path),
test: (url) =>
!(url.hash && url.hash.length > 1 && url.hash !== "#information"),
mount: ".functional > .operation",
specialMount: true,
getContent: async () => {
return _feInstance.currentData.training.description || "复制失败";
},
className:
"lfe-form-sz-middle lcolor-var-blue-3 copy-markdown-btn-contest",
classNameSucc:
"lfe-form-sz-middle lcolor-var-green-3 copy-markdown-btn-contest",
classNameErr:
"lfe-form-sz-middle lcolor-var-red-3 copy-markdown-btn-contest",
selfMount: ".copy-markdown-btn-contest",
},
];
function getRoute() {
const path = location.pathname;
return (
routes.find((r) => {
return (
(typeof r.test === "function" ? r.test(location) : true) &&
r.match(path)
);
}) || null
);
}
function isValidUrl() {
return !!getRoute();
}
function cleanupBtn() {
document
.querySelectorAll("#copy-markdown-mount")
.forEach((el) => el.remove());
}
async function insertBtn() {
const route = getRoute();
if (!route) return false;
const nav = document.querySelector(route.mount || ".user-nav");
if (!nav) return;
if (nav.querySelector(".copy-markdown-btn")) return true;
let btn = document.createElement("button");
btn.textContent = "复制源代码";
btn.type = "button";
btn.id = "copy-markdown-mount";
btn.className =
route.className ||
"lform-size-middle lcolor-var-blue-3 copy-markdown-btn";
btn.addEventListener("click", async () => {
try {
console.log("[DEBUG] route: ", route.name);
const content = await route.getContent();
await navigator.clipboard.writeText(content);
btn.textContent = "复制成功";
btn.className =
route.classNameSucc ||
"lform-size-middle lcolor-var-green-3 copy-markdown-btn";
} catch (e) {
console.error("复制失败:", e);
btn.textContent = "复制失败";
btn.className =
route.classNameErr ||
"lform-size-middle lcolor-var-red-3 copy-markdown-btn";
} finally {
setTimeout(() => {
btn.textContent = "复制源代码";
btn.className =
route.className ||
"lform-size-middle lcolor-var-blue-3 copy-markdown-btn";
}, 600);
}
});
if (route.specialMount) {
nav.insertBefore(btn, nav.lastChild.nextSibling);
} else {
nav.insertBefore(btn, nav.firstChild);
}
return true;
}
function handleUrlChange() {
injectStyle();
if (!isValidUrl()) {
cleanupBtn();
return;
}
const start = Date.now();
const timer = setInterval(() => {
if (!isValidUrl()) {
clearInterval(timer);
cleanupBtn();
return;
}
if (insertBtn()) {
clearInterval(timer);
return;
}
if (Date.now() - start > 3000) clearInterval(timer);
}, 100);
}
const fireUrlChange = () =>
window.dispatchEvent(new Event("userscript:urlchange"));
const _ps = history.pushState,
_rs = history.replaceState;
history.pushState = function (...a) {
const r = _ps.apply(this, a);
fireUrlChange();
return r;
};
history.replaceState = function (...a) {
const r = _rs.apply(this, a);
fireUrlChange();
return r;
};
window.addEventListener("popstate", fireUrlChange);
window.addEventListener("hashchange", fireUrlChange);
window.addEventListener("userscript:urlchange", () => {
cleanupBtn();
setTimeout(handleUrlChange, 0);
});
const init = () => handleUrlChange();
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", init);
} else {
init();
}
})();
喵
// ==UserScript==
// @name 喵
// @namespace http://tampermonkey.net/
// @version 1.3
// @description 喵
// @author 喵
// @match *://*/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
function processInput(target, isContentEditable) {
let value = isContentEditable ? target.textContent : target.value;
let cursorPos = isContentEditable ? getCaretPosition(target) : target.selectionStart;
if (cursorPos < 1 || value[cursorPos - 1] !== '。') return;
// 避免重复:前面已经是“喵。”
if (cursorPos >= 2 && value[cursorPos - 2] === '喵') {
return;
}
const newValue = value.substring(0, cursorPos - 1) + '喵。' + value.substring(cursorPos);
if (isContentEditable) {
const oldScrollTop = target.scrollTop;
target.textContent = newValue;
// 光标放在“喵。”之后 → cursorPos + 1
setCaretPosition(target, cursorPos + 1);
target.scrollTop = oldScrollTop;
} else {
target.value = newValue;
target.setSelectionRange(cursorPos + 1, cursorPos + 1);
}
}
function getCaretPosition(element) {
const selection = window.getSelection();
if (selection.rangeCount === 0) return 0;
const range = selection.getRangeAt(0).cloneRange();
range.selectNodeContents(element);
range.setEnd(selection.getRangeAt(0).endContainer, selection.getRangeAt(0).endOffset);
return range.toString().length;
}
function setCaretPosition(element, pos) {
// 先获取总文本长度,避免越界
const totalLength = element.textContent.length;
if (pos > totalLength) pos = totalLength;
const selection = window.getSelection();
const range = document.createRange();
let charCount = 0;
let found = false;
function walk(node) {
if (found || node.nodeType !== Node.TEXT_NODE) return;
const nodeLen = node.textContent.length;
if (charCount + nodeLen >= pos) {
const offset = pos - charCount;
range.setStart(node, offset);
range.collapse(true);
found = true;
} else {
charCount += nodeLen;
}
}
// 使用 TreeWalker 更可靠地遍历文本节点
const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT, null, false);
let node;
while (!found && (node = walker.nextNode())) {
walk(node);
}
if (!found) {
// 放在末尾
range.selectNodeContents(element);
range.collapse(false);
}
selection.removeAllRanges();
selection.addRange(range);
}
document.addEventListener('input', function(e) {
const t = e.target;
const isEditable = t.isContentEditable;
const isTextInput = (t.tagName === 'INPUT' && t.type === 'text') || t.tagName === 'TEXTAREA';
if (isEditable || isTextInput) {
setTimeout(() => processInput(t, isEditable), 0);
}
}, true);
document.addEventListener('compositionend', function(e) {
if (e.target.isContentEditable) {
setTimeout(() => processInput(e.target, true), 0);
}
}, true);
})();梦回考场
// ==UserScript==
// @name 洛谷 - 梦回考场
// @namespace http://tampermonkey.net/
// @version 0.5
// @description 洛谷题目页面改为NOI/NOIP/CSP经典PDF风格,享受沉浸(致郁)式刷题。
// @author Jerrycyx (Luogu UID 545986)
// @match https://www.luogu.com.cn/problem/*
// @license MPL-2.0
// @grant GM_addStyle
// @require https://scriptcat.org/lib/513/2.1.0/ElementGetter.js#sha256=aQF7JFfhQ7Hi+weLrBlOsY24Z2ORjaxgZNoni7pAz5U=
// @downloadURL https://update.greasyfork.dpdns.org/scripts/543195/%E6%B4%9B%E8%B0%B7%20-%20%E6%A2%A6%E5%9B%9E%E8%80%83%E5%9C%BA.user.js
// @updateURL https://update.greasyfork.dpdns.org/scripts/543195/%E6%B4%9B%E8%B0%B7%20-%20%E6%A2%A6%E5%9B%9E%E8%80%83%E5%9C%BA.meta.js
// ==/UserScript==
(function () {
"use strict";
if (CheckUrl()) {
console.log("[Luogu-RER] URL passed");
MainScript();
}
function CheckUrl() {
const path = window.location.pathname;
const validPrefixes = ["P", "B", "CF", "SP", "AT", "UVA", "T", "U"];
const regex = /^\/problem\/([^/]+)$/;
const match = path.match(regex);
if (!match) return false;
if (!validPrefixes.some(prefix => match[1].startsWith(prefix))) return false;
return true;
}
async function MainScript() {
console.log("[Luogu-RER] MainScript Running.");
const mainElement = await elmGetter.get("#app > .main-container");
mainElement.classList.add("main-element");
mainElement.id = "Main-element";
const [oringinalProblemHeader, oringinalSidebar, problemElement] = await elmGetter.get([
".theme-bg:nth-child(1) > .theme-fg > .columba-content-wrap.header-layout",
"main > .columba-content-wrap > .sidebar-container > .side",
"main > .columba-content-wrap > .sidebar-container > .main > .problem"
], mainElement);
problemElement.classList.add("problem-element");
problemElement.id = "Problem-element";
(async function () {
removeSome(1, "#app > nav");
removeSome(1, "#app > .top-bar");
removeSome(1, "#app > .page-loading");
removeSome(1, "#app > .nav-scrollbar");
GlobalStyles();
ProcessStrong();
ProcessA();
ProcessTable();
ProcessSampleBlocks()
.then(() => removeAll(".io-sample > .io-sample-block button.lform-size-small", problemElement));
ProcessCodeBlocks()
.then(() => {
removeAll(".code-container > button.copy-button", problemElement);
removeAll(".line-numbers-rows", problemElement);
});
ProcessTitles()
.then(ProcessImages);
BuildToolbar()
.then(() => {
removeSome(1, ".problem-block-actions", problemElement);
oringinalSidebar.remove();
});
BuildStat()
.then(BuildHeader)
.then(() => removeSome(2, ".theme-bg", mainElement));
})();
async function GlobalStyles() {
console.log("[Luogu-RER] GlobalStyles Running.");
elmGetter.each("#Problem-element p, #Problem-element ul, #Problem-element ol, #Problem-element .attachments", problemElement, e => {
e.classList.add("custom-common-text");
});
GM_addStyle(`
#Problem-element {
--common-font-family: KaTeX_Main, SimSun, serif;
--strong-font-family: KaTeX_Main, SimHei, sans-serif;
}
.custom-common-text {
font-family: var(--common-font-family);
font-weight: normal;
}
.custom-strong-text {
font-family: var(--strong-font-family);
font-weight: normal;
}
`);
GM_addStyle(`
#Main-element {
margin: 12px 0;
width: auto;
}
#Main-element > main {
background-color: unset;
}
@media (prefers-color-scheme: light) {
body {
background-color: #e6e6e6;
}
}
@media (prefers-color-scheme: dark) {
body {
background-color: #333333;
}
}
#Main-element > main > .columba-content-wrap {
padding: 0px;
}
#Main-element > main > .columba-content-wrap > .sidebar-container {
margin: unset;
}
#Problem-element {
color: black;
width: 100%
max-width: 1191px;
margin: 0 auto;
padding: 77px 141px 156px 141px;
border-radius: 0px;
box-shadow: 0 1px 10px 0px #1a1a1a1a;
}
#Problem-element p:not(li > p) {
text-indent: 2em;
}
#Problem-element p, #Problem-element ul, #Problem-element ol, #Problem-element .attachments {
font-size: 24px;
line-height: 1.6;
margin: unset;
}
#Problem-element ul, #Problem-element ol {
margin-left: 1em;
}
#Problem-element :is(ul, ol) :is(ul, ol) {
margin-left: unset;
}
#Problem-element :is(ul, ol) :is(ul, ol) li::marker {
content: "– ";
}
.katex:not(.katex-display .katex) {
font-size: 1em;
}
#Problem-element ::selection{
background-color: #99c1da; //TODO
mix-blend-mode: multiply;
color: inherit;
}
#Problem-element :focus-visible {
outline: 3px dashed black;
}
`);
}
async function ProcessSampleBlocks() {
console.log("[Luogu-RER] ProcessSampleBlocks Running.");
elmGetter.each("h2.lfe-h2", problemElement, h2 => {
if (h2.textContent.trim() === "输入输出样例") { h2.remove(); }
});
elmGetter.each(".io-sample > .io-sample-block b", problemElement, b => {
const content = b.textContent.trim();
const regex = /^(输入|输出)\s*#(\d+)$/;
const match = content.match(regex);
if (match) {
const type = match[1];
const num = match[2];
const h2 = document.createElement("h2");
h2.classList.add("lfe-h2");
h2.textContent = `样例 ${num} ${type}`;
b.parentNode.parentNode.replaceChild(h2, b.parentNode);
}
});
}
async function ProcessCodeBlocks() {
console.log("[Luogu-RER] ProcessCodeBlocks Running.");
async function ProcessSingleCodeBlocks(e) {
e.classList.add("code-block");
var lines = e.textContent.split("\n");
const fragment = document.createDocumentFragment();
lines.forEach((lineText, idx) => {
const lineContainer = document.createElement("div");
lineContainer.classList.add("custom-code-line");
const lineNumber = document.createElement("span");
lineNumber.classList.add("custom-line-number");
lineNumber.textContent = idx + 1;
const contentSpan = document.createElement("span");
contentSpan.classList.add("custom-code-content");
contentSpan.textContent = lineText === "" ? "\u200B" : lineText;
lineContainer.appendChild(lineNumber);
lineContainer.appendChild(contentSpan);
fragment.appendChild(lineContainer);
});
e.innerHTML = "";
e.appendChild(fragment);
}
elmGetter.each(".io-sample-block pre", problemElement, ProcessSingleCodeBlocks);
//elmGetter.each("pre > code[class^='language-'], pre > code[class*=' language-']", problemElement, ProcessSingleCodeBlocks);
GM_addStyle(`
#Problem-element > .lfe-marked-wrap {
overflow: visible;
}
#Problem-element > .io-sample {
margin: 0px;
display: block;
}
#Problem-element > .io-sample > .io-sample-block {
margin: 0px;
}
#Problem-element pre, #Problem-element code, .custom-pre-line-number {
font-family: Consolas !important; /* SB Luogu don't use that f**king "!important" */
background-color: unset;
}
#Problem-element pre, #Problem-element code {
font-size: 24px;
line-height: 1.5;
}
#Problem-element pre {
margin: 27px -5px 62px 17px;
}
.code-block {
position: relative;
overflow: visible;
}
#Problem-element .custom-line-number {
position: absolute;
text-align: right;
right: 100%;
font-size: 20px;
color: #949494;
padding-right: 14px;
padding-top: 4px;
}
#Problem-element code {
border: none;
}
#Problem-element pre {
border: solid 1px blue;
border-radius: 0;
padding: 5px;
}
`);
}
async function ProcessTitles() {
console.log("[Luogu-RER] ProcessTitles Running.");
elmGetter.each("h1, h2, h3, h4, h5, h6", problemElement, h => {
h.classList.add("H123456", "custom-strong-text");
if (!h.classList.contains("custom-title")) {
const text = h.textContent;
if (text.length > 0) {
if (text[0] !== "【") {
h.insertBefore(document.createTextNode("【"), h.firstChild);
}
if (text[text.length - 1] !== "】") {
h.appendChild(document.createTextNode("】"));
}
}
}
});
GM_addStyle(`
.custom-title {
text-align: center;
}
.H123456 {
font-weight: normal;
}
#Problem-element .H123456:not(.custom-title) {
text-indent: 1em;
}
#Problem-element h1 {
font-size: 36px;
margin: 37px 0px;
border-bottom: unset;
padding-bottom: unset;
}
#Problem-element h2 {
margin-top: 43px;
margin-bottom: 18px;
font-size: 26px;
border-bottom: unset;
padding-bottom: unset;
}
#Problem-element > p.problem-block-actions:not(#problem-element :first-child) {
margin-top: 43px;
margin-bottom: 18px;
}
#Problem-element h3 {
margin-top: 24px;
margin-bottom: 7px;
font-size: 25px;
}
#Problem-element h4, #Problem-element h5, #Problem-element h6 {
margin-top: 10px;
margin-bottom: 7px;
font-size: 24px;
}
`);
}
async function ProcessImages() {
console.log("[Luogu-RER] ProcessImages Running.");
elmGetter.each("p, .H123456", problemElement, e => {
function isValidChainImage(e) {
if (e.tagName === 'IMG') return true;
let current = e;
while (current) {
const childNodes = current.childNodes;
if (childNodes.length !== 1 || childNodes[0].nodeType !== 1) {
return false;
}
current = current.firstElementChild;
if (current && current.tagName === 'IMG') {
return true;
}
}
}
if (isValidChainImage(e)) e.classList.add("single-line-image");
});
GM_addStyle(`
.single-line-image {
text-indent: 0 !important;
text-align: center;
}
`)
}
async function ProcessStrong() {
console.log("[Luogu-RER] ProcessStrong Running.");
elmGetter.each("strong", problemElement, strong => {
strong.classList.add("custom-strong-text");
const fragment = document.createDocumentFragment();
const processNode = (node) => {
if (node.nodeType === Node.TEXT_NODE) {
const text = node.textContent;
const segments = text.split(/([\u4e00-\u9fa5])/);
segments.forEach(segment => {
if (!segment) return;
if (/^[\u4e00-\u9fa5]$/.test(segment)) {
const span = document.createElement("span");
span.classList.add("custom-hanzi-dot");
span.textContent = segment;
const svgNS = "http://www.w3.org/2000/svg";
const svg = document.createElementNS(svgNS, "svg");
svg.setAttribute("class", "custom-dot");
svg.setAttribute("viewBox", "0 0 10 10");
const circle = document.createElementNS(svgNS, "circle");
circle.setAttribute("cx", "5");
circle.setAttribute("cy", "5");
circle.setAttribute("r", "3");
circle.setAttribute("fill", "black");
svg.appendChild(circle);
span.appendChild(svg);
fragment.appendChild(span);
} else {
fragment.appendChild(document.createTextNode(segment));
}
});
} else if (node.nodeType === Node.ELEMENT_NODE) {
fragment.appendChild(node.cloneNode(true));
}
};
strong.childNodes.forEach(node => processNode(node));
strong.innerHTML = "";
strong.appendChild(fragment);
});
GM_addStyle(`
.custom-hanzi-dot {
position: relative;
}
.custom-hanzi-dot svg.custom-dot {
height: 0.16em;
position: absolute;
left: 0.5em;
bottom: -0.05em;
transform: translateX(-50%);
pointer-events: none;
}
`);
}
async function ProcessA() {
console.log("[Luogu-RER] ProcessA Running.");
elmGetter.each("a", problemElement, e => {
e.classList.add("custom-strong-text");
});
GM_addStyle(`
#Problem-element a {
color: black;
font-style: italic;
transition: unset;
}
#Problem-element a:hover {
filter: none;
}
`)
}
async function ProcessTable() {
console.log("[Luogu-RER] ProcessTable Running.");
elmGetter.each("table > thead > tr > th, table > tbody > tr > td", problemElement, e => {
e.classList.add("custom-common-text");
});
GM_addStyle(`
#Problem-element table {
display: table;
margin: 25px auto;
width: fit-content;
}
#Problem-element table > thead > tr {
border-bottom: 3px solid black;
}
#Problem-element table > thead > tr > th, #Problem-element table > tbody > tr > td {
font-size: 24px;
border: 1px solid black;
}
#Problem-element table {
border-top: 4px solid black;
border-bottom: 4px solid black;
border-left: 2px solid white;
border-right: 2px solid white;
}
`)
}
async function BuildToolbar() {
GM_addStyle(`
@media (prefers-color-scheme: light) {
#Custom-toolbar {
--toolbar-bg: #f7f7f7;
--toolbar-border: #bebebe;
--toolbar-text: #262626;
--toolbar-button-on: #e5e5e5;
--toolbar-button-on-bottom: #0072c9;
--toolbar-button-hover: #eaeaea;
--toolbar-button-active: #efefef;
--toolbar-separator-color: #b6b6b6;
--toolbar-shadow: 0px 4.8px 10.8px rgba(0,0,0,0.13), 0px 0px 4.7px rgba(0,0,0,0.11);
}
#Custom-toolbar-setting {
--setting-menu-bg: #ffffff;
--setting-item-hover: #ebebeb;
--setting-menu-hr: #e0e0e0
}
}
@media (prefers-color-scheme: dark) {
#Custom-toolbar {
--toolbar-bg: #3b3b3b;
--toolbar-border: #4f4f4f;
--toolbar-text: #ffffff;
--toolbar-button-on: #4d4d4d;
--toolbar-button-on-bottom: #63ade5;
--toolbar-button-hover: #484848;
--toolbar-button-active: #424242;
--toolbar-separator-color: #737373;
--toolbar-shadow: rgba(0, 0, 0, 0.26) 0px 4.8px 10.8px, rgba(0, 0, 0, 0.22) 0px 0px 4.7px;
}
#Custom-toolbar-setting {
--setting-menu-bg: #292929;
--setting-item-hover: #313131;
--setting-menu-hr: #545454;
}
}
`)
console.log("[Luogu-RER] BuildToolbar Running.");
const toolbar = document.createElement("div");
toolbar.id = "Custom-toolbar";
toolbar.classList.add("custom-toolbar");
const toolbarLeft = document.createElement("div");
toolbarLeft.id = "Custom-toolbar-left";
toolbarLeft.classList.add("custom-toolbar-left");
const toolbarCenter = document.createElement("div");
toolbarCenter.id = "Custom-toolbar-center";
toolbarCenter.classList.add("custom-toolbar-center");
const toolbarRight = document.createElement("div");
toolbarRight.id = "Custom-toolbar-right";
toolbarRight.classList.add("custom-toolbar-right");
toolbar.append(toolbarLeft, toolbarCenter, toolbarRight);
const documentApp = document.querySelector("#app");
documentApp.insertBefore(toolbar, documentApp.firstChild);
function RemoveAllVueDataAttributes(e) {
Array.from(e.attributes).forEach(attr => {
if (attr.name.startsWith('data-v-')) {
e.removeAttribute(attr.name);
}
});
}
function removeAllAttributes(e) {
[...e.attributes].forEach(attr => e.removeAttribute(attr.name));
}
async function InitToolbarLeftLargeButton(selector, parent, id, stateUpdater) {
const button = parent.querySelector(selector);
removeAllAttributes(button);
button.classList.add("custom-toolbar-button", "custom-toolbar-button-large");
button.id = id;
toolbarLeft.appendChild(button);
if (stateUpdater) stateUpdater(button);
return button;
}
const submitButton = await InitToolbarLeftLargeButton(
"div > div > button[type='button']",
oringinalProblemHeader,
"Custom-toolbar-submit",
btn => btn.classList.toggle(
"custom-toolbar-button-on",
window.location.hash === "#submit"
)
);
new MutationObserver(() => submitButton.classList.toggle(
"custom-toolbar-button-on",
window.location.hash === "#submit"
)).observe(document, { subtree: true, childList: true });
const leftSeparator1 = document.createElement("div");
leftSeparator1.classList.add("custom-toolbar-separator");
toolbarLeft.appendChild(leftSeparator1);
async function BuildModalButton(id, modalIndex) {
const button = await InitToolbarLeftLargeButton(
"div > div > button[type='button']",
oringinalProblemHeader,
id
);
const modal = document.querySelectorAll("#app > div.modal")[modalIndex];
const updateState = () => button.classList.toggle(
"custom-toolbar-button-on",
!modal.classList.contains("hide")
);
updateState();
new MutationObserver(updateState).observe(modal, {
attributes: true,
attributeFilter: ["class"]
});
return button;
}
await BuildModalButton("Custom-toolbar-add-list", 0);
await BuildModalButton("Custom-toolbar-copy-problem", 1);
const leftSeparator2 = document.createElement("div");
leftSeparator2.classList.add("custom-toolbar-separator");
toolbarLeft.appendChild(leftSeparator2);
problemElement.querySelectorAll(".problem-block-actions > *").forEach(actionButton => {
const text = actionButton.textContent.trim();
if (text != "展开" && text != "进入 IDE 模式" && text != "显示翻译" && text != "隐藏翻译") {
removeAllAttributes(actionButton);
actionButton.className = "custom-toolbar-a";
toolbarLeft.appendChild(actionButton);
}
if (text == "显示翻译" || text == "隐藏翻译") {
}
});
const rightActionMap = {
"退出比赛模式": { id: "Custom-toolbar-a-exit" },
" 提交记录": { id: "Custom-toolbar-a-record" },
" 查看题解": { id: "Custom-toolbar-a-solution" },
" 题目反馈": { id: "Custom-toolbar-a-feedback" }
};
oringinalSidebar.querySelectorAll("div a").forEach(e => {
RemoveAllVueDataAttributes(e);
e.classList.add("custom-toolbar-a");
const config = rightActionMap[e.textContent];
if (config) {
e.id = config.id;
toolbarRight.appendChild(e);
}
});
const rightSeparator1 = document.createElement("div");
rightSeparator1.classList.add("custom-toolbar-separator");
toolbarRight.appendChild(rightSeparator1);
const setting = document.createElement("div");
setting.id = "Custom-toolbar-setting";
setting.classList.add("custom-toolbar-setting");
toolbarRight.appendChild(setting);
const settingButton = document.createElement("button");
settingButton.id = "Custom-toolbar-setting-button";
settingButton.classList.add("custom-toolbar-setting-button", "custom-toolbar-button");
function CreateSettingSVG() {
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("width", "20");
svg.setAttribute("height", "20");
svg.setAttribute("viewBox", "0 0 20 20");
const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
path.setAttribute("d", "M 1.91 7.38 A 8.5 8.5 0 0 1 3.7 4.3 a 0.5 0.5 0 0 1 0.54 -0.13 l 1.92 0.68 a 1 1 0 0 0 1.32 -0.76 l 0.36 -2 a 0.5 0.5 0 0 1 0.4 -0.4 a 8.53 8.53 0 0 1 3.55 0 c 0.2 0.04 0.35 0.2 0.38 0.4 l 0.37 2 a 1 1 0 0 0 1.32 0.76 l 1.92 -0.68 a 0.5 0.5 0 0 1 0.54 0.13 a 8.5 8.5 0 0 1 1.78 3.08 c 0.06 0.2 0 0.4 -0.15 0.54 l -1.56 1.32 a 1 1 0 0 0 0 1.52 l 1.56 1.32 a 0.5 0.5 0 0 1 0.15 0.54 a 8.5 8.5 0 0 1 -1.78 3.08 a 0.5 0.5 0 0 1 -0.54 0.13 l -1.92 -0.68 a 1 1 0 0 0 -1.32 0.76 l -0.37 2 a 0.5 0.5 0 0 1 -0.38 0.4 a 8.53 8.53 0 0 1 -3.56 0 a 0.5 0.5 0 0 1 -0.39 -0.4 l -0.36 -2 a 1 1 0 0 0 -1.32 -0.76 l -1.92 0.68 a 0.5 0.5 0 0 1 -0.54 -0.13 a 8.5 8.5 0 0 1 -1.78 -3.08 a 0.5 0.5 0 0 1 0.15 -0.54 l 1.56 -1.32 a 1 1 0 0 0 0 -1.52 L 2.06 7.92 a 0.5 0.5 0 0 1 -0.15 -0.54 Z m 1.06 0 l 1.3 1.1 a 2 2 0 0 1 0 3.04 l -1.3 1.1 c 0.3 0.79 0.71 1.51 1.25 2.16 l 1.6 -0.58 a 2 2 0 0 1 2.63 1.53 l 0.3 1.67 a 7.55 7.55 0 0 0 2.5 0 l 0.3 -1.67 a 2 2 0 0 1 2.64 -1.53 l 1.6 0.58 a 7.5 7.5 0 0 0 1.24 -2.16 l -1.3 -1.1 a 2 2 0 0 1 0 -3.04 l 1.3 -1.1 a 7.5 7.5 0 0 0 -1.25 -2.16 l -1.6 0.58 a 2 2 0 0 1 -2.63 -1.53 l -0.3 -1.67 a 7.55 7.55 0 0 0 -2.5 0 l -0.3 1.67 A 2 2 0 0 1 5.81 5.8 l -1.6 -0.58 a 7.5 7.5 0 0 0 -1.24 2.16 Z M 7.5 10 a 2.5 2.5 0 1 1 5 0 a 2.5 2.5 0 0 1 -5 0 Z m 1 0 a 1.5 1.5 0 1 0 3 0 a 1.5 1.5 0 0 0 -3 0 Z");
path.setAttribute("fill", getComputedStyle(toolbar).getPropertyValue("--toolbar-text"));
svg.appendChild(path);
return svg;
}
settingButton.appendChild(CreateSettingSVG());
setting.appendChild(settingButton);
const settingMenu = document.createElement("div");
settingMenu.id = "Custom-toolbar-setting-menu";
settingMenu.classList.add("custom-toolbar-setting-menu", "custom-toolbar-setting-menu-hidden");
setting.appendChild(settingMenu);
let globalClickListener = null;
settingButton.addEventListener("click", function (e) {
e.stopPropagation();
settingMenu.classList.remove("custom-toolbar-setting-menu-hidden");
if (globalClickListener) {
document.removeEventListener("click", globalClickListener);
}
globalClickListener = function (event) {
const isClickInsideMenu = settingMenu.contains(event.target);
const isClickOnButton = settingButton.contains(event.target);
if (!isClickInsideMenu || isClickOnButton) {
settingMenu.classList.add("custom-toolbar-setting-menu-hidden");
document.removeEventListener("click", globalClickListener);
globalClickListener = null;
}
};
setTimeout(() => {
document.addEventListener("click", globalClickListener);
}, 0);
});
function BuildSettingItemSwitch(text, onToggle, initialState = false) {
const settingItem = document.createElement("button");
settingItem.classList.add("custom-toolbar-setting-item");
const checkbox = document.createElement("span");
checkbox.classList.add("custom-toolbar-setting-checkbox");
checkbox.innerHTML = '<svg style="width: 1.25em; height: 1.25em; vertical-align: middle; fill: currentColor; overflow: hidden;" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg"><path d="M365.624235 692.484607 165.695786 492.556159 99.05297 559.198975 365.624235 825.77024 936.850128 254.54537 870.207311 187.902554Z" fill="#b3b3b3"></path></svg>';
const textSpan = document.createElement("span");
textSpan.classList.add("custom-toolbar-setting-text");
textSpan.textContent = text;
const content = document.createElement("div");
content.classList.add("custom-toolbar-setting-content");
content.appendChild(checkbox);
content.appendChild(textSpan);
settingItem.appendChild(content);
let enabled = initialState;
checkbox.style.visibility = enabled ? "visible" : "hidden";
onToggle(enabled, text);
settingItem.addEventListener("click", () => {
enabled = !enabled;
checkbox.style.visibility = enabled ? "visible" : "hidden";
onToggle(enabled, text);
});
settingMenu.appendChild(settingItem);
return {
getState: () => enabled,
setState: (newState) => {
enabled = newState;
checkbox.style.visibility = enabled ? "visible" : "hidden";
onToggle(enabled, text);
},
toggle: () => settingItem.click(),
element: settingItem
};
}
function SwitchStyle(enabled, styleId, enabledStyle, disabledStyle) {
let styleElement = document.getElementById(styleId);
if (!styleElement) {
styleElement = document.createElement("style");
styleElement.id = styleId;
document.head.appendChild(styleElement);
}
const cssRule = enabled ? enabledStyle : disabledStyle;
styleElement.textContent = cssRule;
}
BuildSettingItemSwitch("锁定工具栏", (enabled) => {
SwitchStyle(enabled, "fix-toolbar-style",
"#Custom-toolbar {\
position: sticky;\
top: 0;\
}",
"#Custom-toolbar {\
position: fixed;\
top: 0;\
box-shadow: var(--toolbar-shadow)\
}");
let isNearTop = true, hideTimer = null;
if (enabled) {
showToolbar();
if (hideTimer) {
clearTimeout(hideTimer);
hideTimer = null;
}
}
function showToolbar() {
toolbar.style.top = "0";
if (hideTimer) {
clearTimeout(hideTimer);
hideTimer = null;
}
}
function hideToolbar() {
toolbar.style.top = "-41px";
}
function optimizedThrottle(func, limit) {
let lastRan = 0;
let ticking = false;
return function () {
const context = this;
const args = arguments;
const now = Date.now();
if (now - lastRan >= limit) {
if (!ticking) {
requestAnimationFrame(function () {
func.apply(context, args);
lastRan = now;
ticking = false;
});
ticking = true;
}
}
};
}
const handleMouseMove = optimizedThrottle(function (e) {
if (enabled) return;
const mouseY = e.clientY;
const newState = mouseY <= 41;
if (newState !== isNearTop) {
isNearTop = newState;
if (isNearTop) {
showToolbar();
} else {
if (hideTimer) {
clearTimeout(hideTimer);
hideTimer = null;
}
hideTimer = setTimeout(hideToolbar, 2000);
}
}
}, 100);
window.addEventListener('mousemove', handleMouseMove);
}, true);
BuildSettingItemSwitch("样例复制时带行号", (enabled) => {
SwitchStyle(enabled, "line-number-selection-style",
"#Problem-element .custom-line-number { user-select: all; }",
"#Problem-element .custom-line-number { user-select: none; }"
);
}, false);
BuildSettingItemSwitch("显示时空限制", (enabled) => {
SwitchStyle(enabled, "limit-show-style",
"",
".custom-stat { display: none; }"
);
}, true);
const settingHr1 = document.createElement("hr");
settingHr1.classList.add("custom-setting-hr");
settingMenu.appendChild(settingHr1);
const settingItemInfo = document.createElement("button");
settingItemInfo.classList.add("custom-toolbar-setting-item");
settingItemInfo.id = "Custom-setting-item-info";
settingItemInfo.textContent = "查看题目详细信息(暂不可用)";
settingMenu.appendChild(settingItemInfo);
GM_addStyle(`
#Custom-toolbar {
background-color: var(--toolbar-bg);
border-bottom: 1px solid var(--toolbar-border);
z-index: 10;
width: 100%;
height: 41px;
padding: 0px 4px;
display: flex;
justify-content: space-between;
align-items: center;
box-sizing: border-box;
transition: top 0.5s;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI';
}
#Custom-toolbar-left, #Custom-toolbar-center, #Custom-toolbar-right {
height: 100%;
display: flex;
align-items: center;
}
#Custom-toolbar-left {
justify-content: flex-start;
margin-right: auto;
}
#Custom-toolbar-center {
justify-content: center;
margin-left: auto;
margin-right: auto;
}
#Custom-toolbar-right {
justify-content: flex-end;
margin-left: auto;
}
#Custom-toolbar-setting-menu {
position: absolute;
right: 2px;
width: max-content;
}
.custom-toolbar-button:not(.custom-toolbar-button-large), .custom-toolbar-a {
font-size: 15px;
}
.custom-toolbar-button-large {
font-size: 16px;
}
.custom-toolbar-button, .custom-toolbar-a {
cursor: default;
border: 2px solid transparent;
border-radius: 2px;
padding: 0 8px;
margin: 2px 0px;
max-height: 100%;
display: flex;
white-space: pre-wrap;
justify-content: center;
align-items: center;
color: var(--toolbar-text);
background-color: var(--toolbar-bg);
outline: none;
transition: background-color 0.1s ease-in-out;
}
.custom-toolbar-button {
height: 32px;
}
.custom-toolbar-a {
height: 28px;
}
.custom-toolbar-a a {
color: var(--toolbar-text);
outline: none;
}
.custom-toolbar-button-on {
background-color: var(--toolbar-button-on);
border-bottom-color: var(--toolbar-button-on-bottom);
}
.custom-toolbar-button:hover, .custom-toolbar-a:hover {
background-color: var(--toolbar-button-hover);
filter: unset;
}
.custom-toolbar-button:active, .custom-toolbar-a:active {
background-color: var(--toolbar-button-active);
}
.custom-toolbar-separator {
margin: 0 4px;
width: 1px;
height: 16px;
background-color: var(--toolbar-separator-color);
}
#app > .dropdown.shown {
z-index: 12;
}
#Custom-toolbar-setting-button {
cursor: pointer;
}
#Custom-toolbar-setting-menu {
display: flex;
flex-direction: column;
background-color: var(--setting-menu-bg);
padding: 5px 2px;
border-radius: 10px;
box-shadow: var(--toolbar-shadow);
font-size: 15px;
transition: opacity 0.1s ease, visibility 0.1s ease;
}
.custom-toolbar-setting-menu-hidden {
opacity: 0;
visibility: hidden;
}
.custom-toolbar-setting-checkbox {
margin-right: 0.5em;
}
.custom-toolbar-setting-item {
width: auto;
text-align: left;
padding: 5px 10px;
margin: 0 4px;
background-color: transparent;
color: var(--toolbar-text);
border: unset;
border-radius: 4px;
}
.custom-toolbar-setting-item:hover {
background-color: var(--setting-item-hover);
}
.custom-setting-hr {
border: 1px var(--setting-menu-hr) solid;
width: 100%;
margin: 5px 0;
}
`);
}
async function BuildStat() {
const [timeLimit, memoryLimit] = (await elmGetter.get([
".stat > .field:nth-child(3) > .stat-text.value",
".stat > .field:nth-child(4) > .stat-text.value"
], oringinalProblemHeader)).map(e => e.textContent.trim());
console.log("[Luogu-RER] BuildStat Running.");
const stat = document.createElement("div");
stat.classList.add("custom-stat", "custom-common-text");
const timeStat = document.createElement("div");
timeStat.classList.add("custom-time-stat");
timeStat.textContent = "时间限制:" + timeLimit;
const memoryStat = document.createElement("div");
memoryStat.classList.add("custom-memory-stat");
memoryStat.textContent = "空间限制:" + memoryLimit;
stat.append(timeStat, memoryStat);
problemElement.insertBefore(stat, problemElement.firstChild);
GM_addStyle(`
.custom-stat {
font-size: 24px;
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.custom-time-stat, .custom-memory-stat {
margin-left: 1em;
margin-right: 1em;
}
`);
return stat;
}
async function BuildHeader(stat) {
console.log("[Luogu-RER] BuildHeader Running.");
const titleContent = (await elmGetter.get("h1.lfe-h1", oringinalProblemHeader)).textContent;
const title = document.createElement("h1");
title.classList.add("lfe-h1", "custom-title");
title.textContent = titleContent.substring(titleContent.indexOf(" ") + 1);
problemElement.insertBefore(title, stat);
const customHeaderElement = document.createElement("header");
customHeaderElement.classList.add("custom-header", "custom-common-text");
problemElement.insertBefore(customHeaderElement, title);
const leftText = document.createElement("div");
leftText.classList.add("custom-header-left-text");
leftText.textContent = "洛谷 Luogu";
customHeaderElement.appendChild(leftText);
const rightText = document.createElement("div");
rightText.classList.add("custom-header-right-text");
rightText.textContent = titleContent;
customHeaderElement.appendChild(rightText);
const hrElement = document.createElement("hr");
hrElement.classList.add("custom-header-hr");
customHeaderElement.appendChild(hrElement);
GM_addStyle(`
.custom-header {
font-size: 20px;
display: flex;
flex-wrap: wrap;
margin: 0px 0px 48px 0px;
}
.custom-header-left-text, .custom-header-right-text {
margin: 0px;
}
.custom-header-left-text {
margin-right: auto;
}
.custom-header-hr {
flex-basis: 100%;
border: 1px solid #bfbfbf;
margin: 0px;
}
`);
}
}
async function removeAll(selector, container = document) {
elmGetter.each(selector, container, e => { e.remove(); });
}
async function removeSome(number, selector, container = document) {
for (let i = 1; i <= number; i++) {
const e = await elmGetter.get(selector, container);
e.remove();
}
}
})();板子
数据结构
单向链表模板
struct Node
{
int data;
Node *next;
Node *right;
}
void insertNode(int i, Node *p) {
Node *node = new Node;
node->value = i;
node->next = p->next;
p->next = node;
}
void deleteNode(Node *p) {
p->value = p->next->value;
Node *t = p->next;
p->next = p->next->next;
delete t;
}
并查集
struct DSU
{
int fa[200005];
int siz[200005];
DSU(){for(int i = 1; i <= 200000; i++)fa[i] = i,siz[i] = 1;}
int find(int x){return fa[x] == x ? x : fa[x] = find(fa[x]);}
void unite(int x, int y)
{
x = find(x), y = find(y);
if(x == y)return;
if (siz[x] < siz[y]) swap(x, y);
siz[x] += siz[y];
fa[y] = x;
}
}dsu;平衡树
AVL
int n, root;
struct node
{
int l, r, h, siz, x;
}t[100005];
int cnt;
inline void upd(int p){if(p == 0)return;t[p].siz = 1 + (t[p].l ? t[t[p].l].siz : 0) + (t[p].r ? t[t[p].r].siz : 0);}
inline void upd_h(int p){if(p == 0)return;t[p].h = max((t[p].l ? t[t[p].l].h : 0), (t[p].r ? t[t[p].r].h : 0)) + 1;}
void LL_rorate(int &p)
{
int q = t[p].l;
t[p].l = t[q].r;
t[q].r = p;
t[q].siz = t[p].siz;
upd(p);
upd_h(p);
upd_h(q);
p = q;
}
void RR_rorate(int &p)
{
int q = t[p].r;
t[p].r = t[q].l;
t[q].l = p;
t[q].siz = t[p].siz;
upd(p);
upd_h(p);
upd_h(q);
p = q;
}
void LR_rorate(int &p)
{
RR_rorate(t[p].l);
LL_rorate(p);
}
void RL_rorate(int &p)
{
LL_rorate(t[p].r);
RR_rorate(p);
}
void fix(int &p)
{
if(p == 0) return;
if(t[t[p].l].h - t[t[p].r].h == 2)
{
if(t[t[t[p].l].l].h >= t[t[t[p].l].r].h) LL_rorate(p);
else LR_rorate(p);
}
if(t[t[p].r].h - t[t[p].l].h == 2)
{
if(t[t[t[p].r].r].h >= t[t[t[p].r].l].h) RR_rorate(p);
else RL_rorate(p);
}
upd(p), upd_h(p);
}
void insert(int &p, int x)
{
if(p == 0)
{
p = ++cnt;
t[p].l = t[p].r = 0;
t[p].h = 1;
t[p].siz = 1;
t[p].x = x;
}
else if(x < t[p].x)
{
insert(t[p].l, x);
fix(p);
}
else
{
insert(t[p].r, x);
fix(p);
}
}
void del(int &p, int x)
{
if(p == 0) return;
if(x < t[p].x)
del(t[p].l, x);
else if(x > t[p].x)
del(t[p].r, x);
else
{
if(t[p].l == 0 && t[p].r == 0) p = 0;
else if(t[p].l == 0) p = t[p].r;
else if(t[p].r == 0) p = t[p].l;
else
{
int q = t[p].l;
while(t[q].r) q = t[q].r;
t[p].x = t[q].x;
del(t[p].l, t[q].x);
}
}
fix(p);
}
int query_rank(int p, int x)
{
if(p == 0) return 0;
if(x <= t[p].x) return query_rank(t[p].l, x);
else return query_rank(t[p].r, x) + t[t[p].l].siz + 1;
}
int find(int p, int x)
{
if(p == 0) return 0;
if(x == t[t[p].l].siz + 1) return t[p].x;
if(x <= t[t[p].l].siz) return find(t[p].l, x);
else return find(t[p].r, x - t[t[p].l].siz - 1);
}
int pre(int p, int x)
{
if(p == 0) return 0;
if(t[p].x >= x) return pre(t[p].l, x);
else
{
int op = pre(t[p].r, x);
return (op != 0 ? op : t[p].x);
}
}
int suf(int p, int x)
{
if(p == 0) return 0;
if(t[p].x <= x) return suf(t[p].r, x);
else
{
int op = suf(t[p].l, x);
return (op ? op : t[p].x);
}
}treap
class treap
{
int cnt;
struct node
{
int l, r;
int x, val;
int siz;
}t[1000005];
public:
treap(){t[0].l = t[0].r = t[0].siz = t[0].x = t[0].val = 0;}
int root;
inline void upd(int p){t[p].siz = 1 + (t[p].l ? t[t[p].l].siz : 0) + (t[p].r ? t[t[p].r].siz : 0);}
void l_rorate(int &p)
{
int q = t[p].r;
t[p].r = t[q].l;
t[q].l = p;
t[q].siz = t[p].siz;
upd(p);
p = q;
}
void r_rorate(int &p)
{
int q = t[p].l;
t[p].l = t[q].r;
t[q].r = p;
t[q].siz = t[p].siz;
upd(p);
p = q;
}
void insert(int &p, int x)
{
if(p == 0)
{
p = ++cnt;
t[p].l = t[p].r = 0;
t[p].x = x;
t[p].val = rand();
upd(p);
return;
}
t[p].siz++;
if(x < t[p].x)
{
insert(t[p].l, x);
if(t[t[p].l].val > t[p].val) r_rorate(p);
}
else
{
insert(t[p].r, x);
if(t[t[p].r].val > t[p].val) l_rorate(p);
}
upd(p);
}
void erase(int &p, int x)
{
if(p == 0) return ;
if(x < t[p].x)
{
erase(t[p].l, x);
upd(p);
}
else if(x > t[p].x)
{
erase(t[p].r, x);
upd(p);
}
else
{
if(t[p].l == 0 || t[p].r == 0)
p = (t[p].l ? t[p].l : t[p].r);
else
{
if(t[t[p].l].val < t[t[p].r].val)
{
r_rorate(p);
erase(t[p].r, x);
}
else
{
l_rorate(p);
erase(t[p].l, x);
}
}
if(p) upd(p);
}
}
int query_rank(int p, int x)
{
if(p == 0) return 0;
if(x <= t[p].x) return query_rank(t[p].l, x);
else return query_rank(t[p].r, x) + t[t[p].l].siz + 1;
}
int find(int p, int x)
{
if(p == 0) return 0;
if(x == t[t[p].l].siz + 1) return t[p].x;
if(x <= t[t[p].l].siz) return find(t[p].l, x);
else return find(t[p].r, x - t[t[p].l].siz - 1);
}
int pre(int p, int x)
{
if(p == 0) return 0;
if(t[p].x >= x) return pre(t[p].l, x);
else
{
int op = pre(t[p].r, x);
return (op ? op : t[p].x);
}
}
int suf(int p, int x)
{
if(p == 0) return 0;
if(t[p].x <= x) return suf(t[p].r, x);
else
{
int op = suf(t[p].l, x);
return (op ? op : t[p].x);
}
}
}tree;矩阵
struct Matrix
{
int x, y;
int a[sz][sz];
Matrix(){memset(a, 0, sizeof(a));}
Matrix operator*(const Matrix &T) const
{
Matrix res;
res.x = x, res.y = T.y;
int r;
for (int i = 0; i <= x; ++i)
for (int k = 0; k <= T.y; ++k)
{
r = a[i][k];
for (int j = 0; j <= y; ++j)
res.a[i][j] = (res.a[i][j] + T.a[k][j] * r) % mod;
}
return res;
}
Matrix operator^(int val) const
{
Matrix res, bas;
res.x = res.y = bas.x = bas.y = x;
for (int i = 0; i <= x; ++i)
res.a[i][i] = 1;
for (int i = 0; i <= x; ++i)
for (int j = 0; j <= x; ++j)
bas.a[i][j] = a[i][j];
while (val)
{
if (val & 1)
res = res * bas;
bas = bas * bas;
val >>= 1;
}
return res;
}
}图论
最短路
floyd
for(int k = 1; k <= n; k++)
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
/*if(i != j && i != k && j != k)*/dis[i][j] = min(dis[i][j],dis[i][k]+dis[k][j]);dijkstra
//无负边权
struct edge{int v, w;};
struct node
{
int u, dis;
bool operator > (const node& a) const { return dis > a.dis;}
}op;
int n, m;
int dis[10005], vis[10005];
vector<edge>e[10005];
priority_queue<node, vector<node>, greater<node> >q;
void dijkstra()
{
memset(dis, 0x3f, sizeof(dis));
memset(vis, 0, sizeof(vis));
dis[1] = 0;
q.push({1, 0});
while(!q.empty())
{
op = q.top();q.pop();
int u = op.u;
if(vis[u])continue;
vis[u] = 1;
for(int i = 0; i < e[u].size(); i++)
{
int v = e[u][i].v,w = e[u][i].w;
if (dis[v] > dis[u] + w)
{
dis[v] = dis[u] + w;
q.push({v, dis[v]});
}
}
}
}spfa
//spfa单源+负环
//O(nm)
const int MAXN = 1e4 + 5;
struct edge {
int v, w;
};
vector<edge> e[MAXN];
int dis[MAXN], cnt[MAXN], vis[MAXN];
queue<int> q;
int u,v,w;
int sum;
bool spfa(int n,int s)
{
memset(dis, 0x3f, sizeof(dis));
dis[s] = 0;
q.push(s);
while (!q.empty())
{
int u = q.front();q.pop();
vis[u] = 1;
for (int i = 0; i < e[u].size(); i++)
{
int v = e[u][i].v, w = e[u][i] .w;
if (dis[v] > dis[u] + w)
{
dis[v] = dis[u] + w;
cnt[v] = cnt[u] + 1;
if (cnt[v] >= n)return false;
// if (vis[v])continue;
q.push(v);
vis[v] = 1;
}
}
}
return true;
}最小生成树
prim
//prim算法,以边为基准,适用于稠密图
//与dijkstra相似,一次确定一条边
//此处为堆优化,O((n+m)log n)
struct Edge{int v,w;};
struct node
{
int u,dis;
bool operator>(const node& a) const { return dis > a.dis;}
}op;
int ans;
int n,m;
vector<Edge>e[105];
int a[3007][3007];
int dis[10007],vis[10007];
priority_queue<node,vector<node>,greater<node> >q;
void prim()
{
while(!q.empty())
{
int now=q.top().u;q.pop();
if(vis[now]) continue;
vis[now]=1;
for(int i=1;i<=n;i++)
{
if(i == now)continue;
int v=i;
if(vis[v]==0 && dis[v]>a[now][v])
{
dis[v]=a[now][v];
q.push({v,dis[v]});
}
}
}
}kruskal
//kruskal,瓶颈排序,m log m,适用稀疏图
//码量小,易调试
int n,m;
int ans;
struct edge
{
int u,v,w;
}e[10005];
bool cmp(edge a,edge b){return a.w < b.w;}
int fa[150005];
int find(int x)
{
if(fa[x] != x)
{
fa[x] = find(fa[x]);
}
return fa[x];
}拓扑排序
for(int i = 1; i <= mp.size(); i++)
if(!siz[i]) q.push(i);
while(q.size())
{
int f = q.front();
q.pop();
ans ++;
for(int j : edge[f])
{
siz[j]--;
if(!siz[j]) q.push(j);
}
}LCA
#include <bits/stdc++.h>
#define int long long
using namespace std;
inline int rd(){int x=0,f=1;char ch=getchar();while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();}while (ch>='0'&&ch<='9'){x=x*10+ch-48;ch=getchar();}return x*f;}
constexpr int _ = 5e5 + 5;
int table[19][_];
vector<int> e[_];
int n, m, root, cnt, dfn[_];
inline int get(int x, int y) {return dfn[x] < dfn[y] ? x : y;}
void dfs(int u, int f)
{
dfn[u] = ++cnt;
table[0][cnt] = f;
for (int v : e[u])
if (v != f) dfs(v, u);
}
int lca(int v, int u)
{
if (u == v) return u;
int l = dfn[u], r = dfn[v];
if (l > r) swap(l, r);
++l;
int d = log2(r - l + 1);
return get(table[d][l], table[d][r - (1 << d) + 1]);
}
int u, v;
signed main()
{
n = rd(), m = rd(), root = rd();
for (int i = 2; i <= n; ++i)
{
u = rd(), v = rd();
e[u].push_back(v);
e[v].push_back(u);
}
dfs(root, 0);
for (int i = 1; i <= __lg(n); ++i)
for (int j = 1; j + (1 << i) - 1 <= n; ++j)
table[i][j] = get(table[i - 1][j], table[i - 1][j + (1 << (i - 1))]);
while (m--)
cout << lca(rd(), rd()) << "\n";
return 0;
}背包
分组
for (int k = 1; k <= ttt; k++)
{
for (int i = W; i >= 0; i--)
{
for (int j = 1; j <= sum[k]; j++)
{
if (i >= w[t[k][j]]) dp[i] = max(dp[i],dp[i - w[t[k][j]]] + v[t[k][j]]);
}
}
}多重
for(int i = 1; i <= N; i++)
{
cin>>opv>>opw>>opsum;
int t = 1;
while(opsum > t)
{
n++;
v[n] = opv*t;
w[n] = opw*t;
opsum-=t;
t*=2;
}
if(opsum!=0)
{
n++;
v[n] = opv*opsum;
w[n] = opw*opsum;
}
}
快读
inline int read(){int x=0,f=1;char ch=getchar();while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();}while (ch>='0'&&ch<='9'){x=x*10+ch-48;ch=getchar();}return x*f;}