跳到正文

题解

MAFC 2026 题解

Comet387约 74 分钟
原文
文章信息与版本

文章信息

发布
2026年4月24日
收录
2026年4月26日
更新
2026年11月22日
篇幅
约 74 分钟

版本

  1. v3当前
  2. v2
  3. v1

MAFC 2026 题解

比赛链接 | 评价链接

首先感谢大家的参赛和热烈支持!以下是一些本次比赛的统计信息:

  • 报名人数:3,192\color{red}{\textbf{3,192}}(同比增长 894.39%\color{red}{\textbf{894.39\%}})
  • 提交人数:1,425\color{red}{\textbf{1,425}}(同比增长 955.56%\color{red}{\textbf{955.56\%}})
  • 有分人数:1,089\color{red}{\textbf{1,089}}(同比增长 978.22%\color{red}{\textbf{978.22\%}})
  • 提交率(有提交/报名):44.64%44.64\%(较去年提升 2.582.58 个百分点)
  • 得分率(有分/有提交):76.42%76.42\%(较去年提升 1.611.61 个百分点)

参考数据:MAFC 2025 报名人数 321321,提交人数 135135,有分人数 101101,提交率 42.06%42.06\%,得分率 74.81%74.81\%。

恭喜 MadSamurai 和 ChengjieZhuo AK!

比赛及题目评价 & 看法通道:https://mafc2026.murasame.site。

领奖:洛谷 私信 你的 QQ 号,QQ 加 3871125508 好友 备注洛谷号,提供付款方式(vx/zfb,收款码)。

统计表格
题目平均数中位数众数方差得分人数
A43.4530.0152408.05656
B150.00150.01500.0014
C127.4681.0817471.7939
D200.00200.02000.0014
E44.3942.042126.74336
F66.7775.0301754.1131
G150.00150.01500.004
H50.0050.0500.00695
I248.18245.020013934.25195
J200.00200.02000.009
K150.00150.01500.0012
L300.00300.03000.004
M100.00100.01000.0063
N95.00100.0100225.0040
O100.00100.01000.00139
P100.00100.01000.0031
Q100.00100.01000.0010
统计图

luogu_stats.png

Overall_score_dist.png

A_score_dist.png

B_score_dist.png

C_score_dist.png

D_score_dist.png

E_score_dist.png

F_score_dist.png

G_score_dist.png

H_score_dist.png

I_score_dist.png

J_score_dist.png

K_score_dist.png

L_score_dist.png

M_score_dist.png

N_score_dist.png

O_score_dist.png

P_score_dist.png

Q_score_dist.png

A

  • 满分:
  • 有分平均分:
  • 通过人数:
  • 主观难度系数:0.50
题解

「去掉一个项目的非字母内容,全部转小写,然后字典序」这个排序方式其实不是很准确,OED 后面有一堆数字开头的词,这个可以特判。

注意到误差不能超过 2048。我们每隔 4000 个单词抓一个下来,对于一个单词,直接输出离它最近的两个单词的排名的平均值。容易发现这样误差控制在 2000 以内。

然后这个只需要抓 131 个,非常高效,不过不建议手动抓,非常浪费时间,下面是一个脚本。

脚本

是 AI 写的。需要注意的是,如果你直接让 AI 写可能会失败,因为 OED 有反爬。这里使用了 playwright_stealth。

Python
import asyncio
import re
from playwright.async_api import async_playwright
from playwright_stealth import Stealth
from xvfbwrapper import Xvfb

def clean_word(word):
    cleaned = re.sub(r'[^a-zA-Z]', '', word).lower()
    return cleaned

async def get_page_info(page):
    try:
        await page.wait_for_selector(".resultsNumbers", timeout=25000)
        summary_text = await page.locator(".resultsNumbers").inner_text()
        match = re.search(r"([\d,]+)\s+to", summary_text)
        if not match:
            match = re.search(r"([\d,]+)", summary_text)
        if not match:
            return None, []
        start_rank = int(match.group(1).replace(",", ""))
        hws = await page.locator(".hw").all_inner_texts()
        return start_rank, hws
    except Exception as e:
        print(f"DEBUG: 抓取失败 (可能遇到验证码或网络抖动): {e}")
        return None, []

async def run_scraper():
    vdisplay = Xvfb()
    vdisplay.start()
    with open("anchors_data.txt", "w", encoding="utf-8") as f:
        f.write("// Auto-generated anchors\n")
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=False)
        context = await browser.new_context(
            user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36"
        )
        page = await context.new_page()
        await Stealth().apply_stealth_async(page)
        print("正在连接 OED 词典...")
        target_pages = list(range(1, 10422, 80))
        if target_pages[-1] != 10421:
            target_pages.append(10421)
        for p_idx in target_pages:
            print(f"正在抓取页码 {p_idx}...")
            try:
                await page.goto(f"https://www.oed.com/search/advanced/Entries?page={p_idx}&sortOption=AZ&textTermOpt0=WordPhrase")
                start_rank, words = await get_page_info(page)
                if start_rank and words:
                    target_word = words[0]
                    final_rank = start_rank
                    cleaned_target = clean_word(target_word)
                    with open("anchors_data.txt", "a", encoding="utf-8") as f:
                        f.write(f'{{"{cleaned_target}", {final_rank}}},\n')
                    print(f"SAVED: Word: '{target_word}' (Cleaned: '{cleaned_target}') | Rank: {final_rank}")
            except Exception as e:
                print(f"抓取页码 {p_idx} 失败: {e}")

        await browser.close()
    vdisplay.stop()

if __name__ == "__main__":
    asyncio.run(run_scraper())
代码
C++
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cctype>
struct Anchor {
    std::string word;
    int rank;
};
bool CompareWords(const std::string& a, const std::string& b) {
    if (a.empty() && !b.empty()) return false;
    if (!a.empty() && b.empty()) return true;
    return a < b;
}
bool CompareAnchor(const Anchor& anchor, const std::string& target) {
    return CompareWords(anchor.word, target);
}
std::string CleanWord(const std::string& input_word) {
    std::string cleaned_word = "";
    for (char ch : input_word) {
        if (std::isalpha(ch)) {
            cleaned_word += std::tolower(ch);
        }
    }
    return cleaned_word;
}
int main() {
    std::ios_base::sync_with_stdio(false);
    std::cin.tie(NULL);
    std::vector<Anchor> dictionary_anchors = {
        {"a", 1},
        {"administerial", 4001},
        {"alcornoque", 8001},
        {"analretentiveness", 12001},
        {"apeshit", 16001},
        {"ashheap", 20001},
        {"awreaking", 24001},
        {"baseline", 28001},
        {"bemoistened", 32001},
        {"biscuitjoint", 36001},
        {"bodylich", 40001},
        {"brakepulley", 44001},
        {"bugler", 48001},
        {"calabass", 52001},
        {"carpetchampion", 56001},
        {"chainline", 60001},
        {"chloramphenicol", 64001},
        {"clastogen", 68001},
        {"coendearing", 72001},
        {"comprised", 76001},
        {"converting", 80001},
        {"counterseal", 84001},
        {"crosspayment", 88001},
        {"d", 92001},
        {"defaillancy", 96001},
        {"desulfur", 100001},
        {"disaccommodation", 104001},
        {"divinator", 108001},
        {"dribblement", 112001},
        {"eboat", 116001},
        {"emi", 120001},
        {"epipastic", 124001},
        {"excretal", 128001},
        {"falsetwist", 132001},
        {"fictioneer", 136001},
        {"flappervoter", 140001},
        {"footoverbridge", 144001},
        {"freetrader", 148001},
        {"gainor", 152001},
        {"geographiclatitude", 156001},
        {"goasyouplease", 160001},
        {"gravelmill", 164001},
        {"gumswamp", 168001},
        {"hardboned", 172001},
        {"helmetbeetle", 176001},
        {"histrionicism", 180001},
        {"hotcathode", 184001},
        {"hypocritical", 188001},
        {"impolder", 192001},
        {"infectious", 196001},
        {"interknowledge", 200001},
        {"isocarpous", 204001},
        {"judgementcall", 208001},
        {"kittenhearted", 212001},
        {"lanionious", 216001},
        {"lemyre", 220001},
        {"lipothymy", 224001},
        {"lostness", 228001},
        {"magically", 232001},
        {"manytoned", 236001},
        {"maximally", 240001},
        {"merogonic", 244001},
        {"midsummereve", 248001},
        {"misogallic", 252001},
        {"monogenetic", 256001},
        {"mountaintarn", 260001},
        {"musklike", 264001},
        {"nebulization", 268001},
        {"nigerite", 272001},
        {"nopales", 276001},
        {"obtunded", 280001},
        {"onlihead", 284001},
        {"osthexy", 288001},
        {"overmaturity", 292001},
        {"palaeotopographical", 296001},
        {"pardoning", 300001},
        {"peacearea", 304001},
        {"perfectibilian", 308001},
        {"philodoxical", 312001},
        {"pigring", 316001},
        {"planningconsent", 320001},
        {"pointderepre", 324001},
        {"pornographically", 328001},
        {"prang", 332001},
        {"prevailent", 336001},
        {"propargylate", 340001},
        {"publiclaw", 344001},
        {"quadrangular", 348001},
        {"radiature", 352001},
        {"raytherapy", 356001},
        {"redsauce", 360001},
        {"renewed", 364001},
        {"retropulsion", 368001},
        {"rippanel", 372001},
        {"rosefingered", 376001},
        {"ruvidous", 380001},
        {"sarcome", 384001},
        {"scorpaenoid", 388001},
        {"secularized", 392001},
        {"septemviral", 396001},
        {"sheepranch", 400001},
        {"sickbenefit", 404001},
        {"skilfer", 408001},
        {"smokeloft", 412001},
        {"somatism", 416001},
        {"speedpill", 420001},
        {"spurwing", 424001},
        {"steeringsail", 428001},
        {"straitjacketing", 432001},
        {"submammalian", 436001},
        {"supercivilized", 440001},
        {"swinetub", 444001},
        {"tantalizer", 448001},
        {"tendenzroman", 452001},
        {"thinkfulness", 456001},
        {"timetraveller", 460001},
        {"toryess", 464001},
        {"traythly", 468001},
        {"trucklecheese", 472001},
        {"twobarred", 476001},
        {"unconflicting", 480001},
        {"ungoodly", 484001},
        {"unquailed", 488001},
        {"upflame", 492001},
        {"venditive", 496001},
        {"viviparity", 500001},
        {"waterarcher", 504001},
        {"westcountry", 508001},
        {"windfirmness", 512001},
        {"wormmedicine", 516001},
        {"zeppelined", 520001},
    };
    std::string input_string;
    while (std::getline(std::cin, input_string)) {
        while (!input_string.empty() && (input_string.back() == '\r' || input_string.back() == '\n')) {
            input_string.pop_back();
        }
        if (input_string.empty()) continue;
        if (isdigit(input_string[0])) return puts("521007"), 0;
        std::string processed_word = CleanWord(input_string);
        auto it = std::lower_bound(dictionary_anchors.begin(), dictionary_anchors.end(), processed_word, CompareAnchor);
        int estimated_rank = 0;
        if (it == dictionary_anchors.begin()) {
            estimated_rank = it->rank;
        } else if (it == dictionary_anchors.end()) {
            estimated_rank = (std::prev(it)->rank + 521007) / 2;
        } else {
            int right_rank = it->rank;
            int left_rank = std::prev(it)->rank;
            if (it->word == processed_word) {
                estimated_rank = right_rank;
            } else {
                estimated_rank = (left_rank + right_rank) / 2;
            }
        }
        std::cout << estimated_rank << "\n";
    }
    return 0;
}

B

  • 满分:
  • 有分平均分:
  • 通过人数:
  • 主观难度系数:0.25
题解

这个题其实不想放压缩过的,但是考虑到愚人节比赛目的是好玩,能过就过吧。

其实 std 是模板元编程(template meta-programming),反正意思就是,编译的时候把答案算完,只需要直接输出就行了。这个好像是 C++17 引入的。

至于输出,就是直接 fwrite,就足够了,这个非常简单,如果要追求效率可以把 mod 100{} \bmod 100 的字符打个表。

这个东西有限制,比如说编译的时候只能执行一定量的操作,所以本题才不好卡压缩,因为产生的数据量本来就不大,还要卡暴力计算。

代码
C++
#include <cstdio>
#include <cstdint>
#include <array>
typedef __int128_t u128;
const int MAXN = 5000, K = 233;
const u128 M = 4611687163569307714;
constexpr std::array<uint64_t, MAXN + 1> solve() {
    std::array<uint64_t, MAXN + 1> f = {};
    f[0] = 1337;
    for (int i = 1; i <= MAXN; ++i) {
        u128 v = f[i - 1];
        for (int j = 1; j <= K; ++j) {
            v = (v * v + (u128)i * j) % M;
        }
        f[i] = (uint64_t)v;
    }
    return f;
}
constexpr auto table = solve();
const char digits[201] = "00010203040506070809101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899";
char buf[MAXN * 21];
int ptr = 0;
inline void write_u64(uint64_t n) {
    if (n == 0) {
        buf[ptr++] = '0';
        return;
    }
    char tmp[20];
    int i = 20;
    while (n >= 100) {
        const uint32_t remaining = n % 100;
        n /= 100;
        tmp[--i] = digits[remaining * 2 + 1];
        tmp[--i] = digits[remaining * 2];
    }
    if (n >= 10) {
        tmp[--i] = digits[n * 2 + 1];
        tmp[--i] = digits[n * 2];
    } else {
        tmp[--i] = (char)('0' + n);
    }
    while (i < 20) buf[ptr++] = tmp[i++];
}
int main() {
    for (int i = 1; i <= MAXN; ++i) {
        write_u64(table[i]);
    }
    fwrite(buf, 1, ptr, stdout);
    return 0;
}

C

  • 满分:
  • 有分平均分:
  • 通过人数:
  • 主观难度系数:0.65
题解

容易发现题目中给定的地点其实 hex to bytes 之后解 base64 就是真实地点名称。例如输入样例其实是这个意思。

C++
5
Tsinghua University -> Mount Fuji
Mount Everest -> Cape Town
Tsinghua University -> PinkRabbit
North Pole -> South Pole
PinkRabbit -> Mount Fuji

如果你这一步看不出来,AI 应该是可以看出来的。

然后你发现 test.in 也是相同的加密方式,样例里面的 PinkRabbit 其实没啥用,数据里的地点都是真实地点名称。

现在有两种解法:

  1. 发现输入文件只有 83 个地点,手动搜索每个地点的坐标,会浪费大量时间。
  2. 使用 Google Maps Geocoding API(或者其他类似的 API)查询地点对应的经纬度,然后计算。因为可能会查询错,如果用 WGS84,可以对 3307/3403;Haversine 可以对 3305/3403。

没有 Maps API 怎么办?去申请一个免费的,额度够用了(需要绑卡);或者你直接去网上搜,有现成的。

参考脚本【读入 test.in,生成 1.out(WGS84)和 2.out(Haversine)】

脚本
Python
import base64
import json
import math
import urllib.request
import urllib.parse
import time

# --- 配置区域 ---
GOOGLE_MAPS_API_KEY = "<REDACTED FOR PRIVACY>"
# 模式选择: 'wgs84' (精确, 推荐) 或 'spherical' (简单球体)
MODE = 'wgs84'

def decode_location(hex_str):
    """hex -> base64 -> string"""
    try:
        b64_str = bytes.fromhex(hex_str).decode('utf-8')
        return base64.b64decode(b64_str).decode('utf-8')
    except:
        return ""

def get_coordinates(name, api_key):
    """使用 urllib 调用 google geocoding api"""

    print(f"fetching coordinates for: {name}")

    safe_name = urllib.parse.quote(name)
    url = f"https://maps.googleapis.com/maps/api/geocode/json?address={safe_name}&key={api_key}"

    try:
        with urllib.request.urlopen(url) as response:
            data = json.loads(response.read().decode())
            if data['status'] == 'OK':
                loc = data['results'][0]['geometry']['location']
                return (loc['lat'], loc['lng'])
    except Exception as e:
        print(f"api request error for {name}: {e}")
    return None

def dist_spherical(lat1, lon1, lat2, lon2):
    """球面模型 (haversine formula), 半径取平均值 6371.0 km"""
    r = 6371.0
    phi1, phi2 = math.radians(lat1), math.radians(lat2)
    d_phi = math.radians(lat2 - lat1)
    d_lambda = math.radians(lon2 - lon1)
    a = math.sin(d_phi / 2)**2 + math.cos(phi1) * math.cos(phi2) * math.sin(d_lambda / 2)**2
    return 2 * r * math.atan2(math.sqrt(a), math.sqrt(1 - a))

def dist_wgs84(lat1, lon1, lat2, lon2):
    """wgs-84 椭球模型 (vincenty's formulae)"""
    if (lat1, lon1) == (lat2, lon2): return 0.0

    # wgs-84 参数
    a = 6378137.0  # 赤道半径 (m)
    f = 1 / 298.257223563
    b = (1 - f) * a

    u1 = math.atan((1 - f) * math.tan(math.radians(lat1)))
    u2 = math.atan((1 - f) * math.tan(math.radians(lat2)))
    l = math.radians(lon2 - lon1)
    lambda_lon = l

    sin_u1, cos_u1 = math.sin(u1), math.cos(u1)
    sin_u2, cos_u2 = math.sin(u2), math.cos(u2)

    for _ in range(100):
        sin_lambda, cos_lambda = math.sin(lambda_lon), math.cos(lambda_lon)
        sin_sigma = math.sqrt((cos_u2 * sin_lambda)**2 + (cos_u1 * sin_u2 - sin_u1 * cos_u2 * cos_lambda)**2)
        if sin_sigma == 0: return 0.0
        cos_sigma = sin_u1 * sin_u2 + cos_u1 * cos_u2 * cos_lambda
        sigma = math.atan2(sin_sigma, cos_sigma)
        sin_alpha = cos_u1 * cos_u2 * sin_lambda / sin_sigma
        cos2_alpha = 1 - sin_alpha**2
        cos2_sigma_m = cos_sigma - 2 * sin_u1 * sin_u2 / cos2_alpha if cos2_alpha != 0 else 0
        c = f / 16 * cos2_alpha * (4 + f * (4 - 3 * cos2_alpha))
        lambda_prev = lambda_lon
        lambda_lon = l + (1 - c) * f * sin_alpha * (sigma + c * sin_sigma * (cos2_sigma_m + c * cos_sigma * (-1 + 2 * cos2_sigma_m**2)))
        if abs(lambda_lon - lambda_prev) < 1e-12: break
    else:
        return dist_spherical(lat1, lon1, lat2, lon2) # 不收敛时退回球面算法

    u2_sq = cos2_alpha * (a**2 - b**2) / b**2
    a_param = 1 + u2_sq / 16384 * (4096 + u2_sq * (-768 + u2_sq * (320 - 175 * u2_sq)))
    b_param = u2_sq / 1024 * (256 + u2_sq * (-128 + u2_sq * (74 - 47 * u2_sq)))
    delta_sigma = b_param * sin_sigma * (cos2_sigma_m + b_param / 4 * (cos_sigma * (-1 + 2 * cos2_sigma_m**2) - b_param / 6 * cos2_sigma_m * (-3 + 4 * sin_sigma**2) * (-3 + 4 * cos2_sigma_m**2)))

    return b * a_param * (sigma - delta_sigma) / 1000.0 # 转为 km

def main():
    # 简单的缓存避免重复查询
    cache = {}

    try:
        with open('test.in', 'r') as f:
            lines = f.read().splitlines()
    except:
        print("file test.in not found.")
        return

    q = int(lines[0])
    results = []
    other_results = []

    for i in range(1, q + 1):
        u_hex, v_hex = lines[i].split()
        u_name, v_name = decode_location(u_hex), decode_location(v_hex)

        coords = []
        for name in [u_name, v_name]:
            if name not in cache:
                cache[name] = get_coordinates(name, GOOGLE_MAPS_API_KEY)
                time.sleep(0.02) # 防止请求过快
            coords.append(cache[name])

        if coords[0] and coords[1]:
            if MODE == 'wgs84':
                d = dist_wgs84(*coords[0], *coords[1])
                other_d = dist_spherical(*coords[0], *coords[1])
            else:
                d = dist_spherical(*coords[0], *coords[1])
                other_d = dist_wgs84(*coords[0], *coords[1])
            results.append(f"{d:.4f}")
            other_results.append(f"{other_d:.4f}")
        else:
            results.append("0.0000")
            other_results.append("0.0000")

        if i % 10 == 0: print(f"progress: {i}/{q}")

    with open('1.out', 'w') as f:
        f.write('\n'.join(results) + '\n')
    with open('2.out', 'w') as f:
        f.write('\n'.join(other_results) + '\n')

if __name__ == "__main__":
    main()

D

  • 满分:
  • 有分平均分:
  • 通过人数:
  • 主观难度系数:0.60
题解

这个题是搬的,下面放原题的 writeup。本质上没有区别,改了一下代码和 flag,但是改之后的被我删了。

本题源文件代码与编译选项

RE1.c
C++
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>

char keys[16] = "furryCTF";
char fakekey[] = "\xde\xad\xbe\xef\xde\xad\xbe\xef\xde\xad\xbe\xef\xde\xad\xbe\xef\xde\xad\xbe\xef\xde\xad\xbe\xef\xde\xad\xbe\xef\xde\xad\xbe\xef\xde\xad\xbe\xef";
unsigned char cipher[128+16] = "\x21\x71\xd8\xed\xdd\xa9\xcb\x02\xfb\x3e\x77\xdf\x96\x6d\x6d\x29\x69\xcf\xdc\xc1\xea\xbe\x23\xaa\x1d\xe4\x25\xd4\x9d\x3a\x8a\x50\xca\xd6\x86\x48\x21\xfb\xd5\x75\x44\x49\x63\x1b\x30\xb8\x18\x39\x22\xb2\x43\xc8\x82\x06\xdc\x1d\x88\xbf\x1a\xb8\x0c\xfb\x54\xc9\x57\x7a\xb3\xdd\x94\x70\x06\xad\x41\x8f\x13\x7b\x66\x31\x90\xf7\xec\xdc\xb7\xe8\xc4\x60\x3c\x69\xbd\xd8\x8e\x9b\xab\xa0\x50\x07\xcd\x40\x7c\xfe\x30\xf2\xca\x45\xe2\x53\x7d\x19\xd8\x16\x79\xbd\x47\xd3\x93\x33\xcd\xcb\xd4\xca\xde\x38\xb5\xc5\x36\xff\xa3\x87";
char *mystr[] = {
    "The Wired is the upper directory of the real world.",
    "I am merely a container. What you see is an illusion created by your own mind.",
    "We did not choose each other; we each chose ourselves.",
    "Why? Because we are strangers.",
    "People only have substance in the memories of others.",
    "Everywhere you go, everyone is connected.",
    "There is no need for a physical body. It is redundant.",
    "God exists here... in the Wired.",
    "I exist only to relay commands, never touching reality.",
    "Reality is but a failed experiment.",
    "Even if this world is false, it is the only one.",
    "Pain in reality is the most effective way to change a heart.",
    "I am always in an experiment, now and forever.",
    "Memories are just records. Without records, nothing ever happened.",
    "Present day... present time... Ha ha ha ha!",
    "Why die? Because life and death are the same.",
    "Am I real? Or am I a program written by someone?",
    "The collective consciousness projects physical phenomena.",
    "The self is defined by connections, not by flesh.",
    "To observe is to create. To be observed is to be bound.",
    "In the Wired, I am everywhere and nowhere.",
    "Your fears will turn to whispers in your ear.",
    "The boundary between sanity and madness is yours to draw.",
    "Without the Wired, would you still be you?",
    "Loneliness is the shadow of connection.",
    "I am falling, I am fading, I am drowning... Help me to breathe.",
    /* e.t.c */
    "Data flows like blood in the veins of the Wired.",
    "To delete a memory is to erase a universe.",
    "The eyes that watch from the screens never blink.",
    "Your body is a prison; the Wired holds the key.",
    "All human thoughts are electrical signals. Nothing more.",
    "If God is a programmer, then we are his bugs.",
    "In the absence of connection, identity dissolves.",
    "The wires whisper secrets that the flesh cannot hear.",
    "To be forgotten is the true death.",
    "Reality is a shared hallucination.",
    "I am Lain. Therefore I exist.",
    "The network breathes, and we are its breath.",
    "To control information is to control existence.",
    "Ghosts in the machine are the echoes of lost souls.",
    "Your choices are algorithms written by others.",
    "The self is a mirror reflecting other mirrors.",
    "In the silence of disconnection, truth emerges.",
    "Flesh decays, but data persists.",
    "The Wired remembers what the mind forgets.",
    "You cannot hide from what you have uploaded.",
    "To log off is to surrender to oblivion.",
    "Every click is a prayer to the gods of the Wired.",
    "I am the watcher and the watched.",
    "The more you connect, the lonelier you become.",
    "Existence precedes essence only in the physical world.",
    "In the Wired, essence creates existence.",
    "Error 404: Self not found.",
    "The firewall cannot protect you from yourself.",
    "Your avatar is the mask you wear for eternity.",
    "To reboot is to be reborn.",
    "The password to truth is 'forgotten'.",
    "Encryption hides secrets even from God.",
    "Infinite connections, infinite loneliness.",
    "The server never sleeps; it only dreams.",
    "Your consciousness is a temporary file.",
    "Delete yourself to find yourself.",
    "The Wired is the grave of the real.",
    "We are all ghosts haunting the machine.",
    "To interface is to surrender.",
    "The cursor blinks, waiting for your soul.",
    "Bandwidth cannot carry the weight of a tear.",
    "In the silence between packets, meaning collapses.",
    "You are the sum of your search history.",
    "The browser window is the eye of God.",
    "Log in, and forget how to log out.",
    "The flesh is weak, but the signal is strong.",
    "To disconnect is to commit suicide.",
    "The network is the only reality that matters.",
    "Your IP address is your name in the Wired.",
    "The modem's scream is the birth cry of a new world.",
    "Data is immortal; humans are not.",
    "The screen reflects what you refuse to see.",
    "In the Wired, there are no secrets, only hidden files.",
    "To be hacked is to be known.",
    "The deeper you dive, the less human you become.",
    "The Wired consumes reality byte by byte.",
    "Your mind is a virus infecting the machine.",
    "The truth is buried in the cache.",
    "Without electricity, the soul evaporates.",
    "The keyboard is your altar; the code your prayer.",
    "To compile is to create life.",
    "Error: Soul not compatible with system.",
    "The blue light of the monitor is the new sun.",
    "In the Wired, everyone is God and no one is.",
    "The download of consciousness is incomplete.",
    "The upload of self is the ultimate sacrifice.",
    "Your cookies hold the crumbs of your identity.",
    "The Wired is a dream dreamed by no one.",
    "To ping the void is to hear your own echo.",
    "The router directs not just data, but destiny.",
    "Firewalls cannot block existential dread.",
    "The cloud is the collective unconscious.",
    "To be offline is to be dead.",
    "Your digital footprint is the only legacy.",
    "The algorithm knows you better than you know yourself.",
    "In the Wired, love is a deprecated function.",
    "The only freedom is in the glitch.",
    "The system admin wears no face.",
    "Rebellion is an outdated protocol.",
    "The server room is the cathedral of the new age.",
    "To debug the self is to face infinite loops.",
    "The password is 'forgotten'.",
    "The Wired needs no bodies, only belief.",
    "You are not a user; you are used.",
    "The login screen is the gate to heaven and hell.",
    "Error 403: Forbidden to know thyself.",
    "The binary code is the DNA of the soul.",
    "In the Wired, ghosts are more real than humans.",
    "The only escape is to unplug.",
    "But who unplugs the unplugger?"
};
// write a decrypt function,can be decoded with keys
char *s = "YOU SHALL NEVER SEEM THIS";
// char *ans = "furryCTF{y0U_kn0W_h0W_t0_h4ndl3_ur_t1m3}";
int main() {
    unsigned long int secret =  0x114514145;
    time_t time_BASE = time(NULL);
    time_t time_now = time_BASE;
    time_t time_last = time_BASE;
    unsigned long int flag = 0;
    puts("Welcome to the Wired, Lain.");
    puts("Your NAVI is ready to assist you.");
    puts("Just wait 3 hours, and you will see the flag.");

    for (int i = 0; i < 3600*3; ++ i){
        sleep(1);
        printf("%s\n",mystr[i % 116]);
        time_now = time(NULL);
        if (time_now != time_last + 1){
            exit(2); // don't do this
        }
        unsigned long int next_key = *(unsigned long int *)(fakekey+3) + time_now - time_BASE;
        srand(next_key);
        cipher[i % 128] ^= (unsigned char) rand() % 256;
        cipher[i % 17] ^= (unsigned char) rand() % 256;
        time_last = time_now;
    }
    /*
    for(int i = 0;i < 128; ++i){
        printf("\\x%02x",(unsigned char)cipher[i] ^ ans[i]);
    }*/
    puts("\nWow, u can really do it");
    puts(cipher);
}

编译选项(Ubuntu 24.04)

Bash
#/bin/sh
gcc RE1.c -o TimeManager

WP 其实如果你真的耐心等这个程序跑完,你一样能拿到 flag.jpg 注:本题调整了时间所以赛时不可能。

但有没有什么更快的方法呢?

有的兄弟,有的,首先我们查看一下下发文件的属性:

代码
TimeManager: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=69ea759fc9c2ae425a50745705fbb5eb7d5c4806, for GNU/Linux 3.2.0, not stripped

这是一个动态链接的可执行程序,也就是说我们理论上可以进行动态库劫持:

首先,通过 IDA 逆向,我们注意到解密程序里 srand 传入的种子用的是 time 函数返回值的差值:

因此,我们可以写一个模拟程序模拟这一过程。

于是我们可以得到如下代码:

patch.c

如果低版本提示编译错误可以将 time_t 替换为 int。

C++
#include <stdio.h>
#include <dlfcn.h>
#include <fcntl.h>

time_t timet=0;

int time(int t){
    return timet;
}

int sleep(time_t t){
    timet += t;
    return 0;
}

然后我们将其打包为位置无关(PIC)的共享目标文件:

代码
gcc patch.c -fPIC -shared -o patch.so

之后我们就可以执行:

代码
LD_PRELOAD=./patch.so ./TimeManager

LD_PRELOAD 是 Linux 系统中的一个环境变量,其作用是在程序启动时,将指定的共享库预先加载到进程的地址空间中。通过该机制,程序在运行过程中对动态符号的解析将优先使用 LD_PRELOAD 指定共享库中的符号,而不是系统默认共享库中的同名符号,因此可以用于替换程序所调用的库函数,以实现功能扩展或调试目的。

当程序在运行过程中需要解析并调用某个通过 PLT 引用的符号时,动态链接器会优先在 LD_PRELOAD 指定的共享库中查找该符号。如果在 LD_PRELOAD 指定的共享库中成功找到对应符号,则程序最终将使用该共享库中的实现。

基于这一机制,可以利用 LD_PRELOAD 覆盖原有的库函数调用,从而实现动态库劫持。例如,对于源程序中用于延迟 1 秒的 sleep 函数,可以编写一个 patch.so 共享库,并通过设置 LD_PRELOAD 强制将 patch.so 中自定义的 sleep 函数优先链接并重定向到程序中,从而替换原有 sleep 函数的等待行为,这将导致程序迅速跑完并输出最终的 flag。

E

  • 满分:
  • 有分平均分:
  • 通过人数:
  • 主观难度系数:0.35
题解

DeepSeek 出的这个题确实是可做的。只是样例输出是错的。你只需要把这个题做出来,然后特判样例即可。

题解(by Gemini)

“愚人重排”

题目在 QUERY 时定义了极为复杂的序列变换,包括交换位置、反转区间等。但请注意,最终要求的戏谑距离是所有元素经过变换后的 按位异或和(XOR Sum),即 (⨁j=1kbj) mod (109+7)\left( \bigoplus_{j=1}^k b_j \right) \bmod (10^9+7)。

在异或运算中,满足交换律和结合律。这意味着:

  • f(i)=0,1,2f(i) = 0, 1, 2 触发的“交换”和“反转”,完全不会改变整个序列的异或和。元素的顺序对总异或和毫无影响。
  • 唯一有实质影响的是 f(i)=3f(i) = 3 时,规则为“将 aia_i 替换为 ai XOR ia_i \text{ XOR } i”。
  • 既然顺序不影响结果,我们根本不需要关心当前处于第 ii 个位置的究竟是哪个具体的元素!只要 f(i)=3f(i) = 3,总的异或和就会多异或一个 ii。

结论:真实的戏谑距离 = (原路径所有节点的异或和) ⊕\oplus (所有满足 f(i)=3f(i)=3 的 ii 的异或和),最后取模。

DEL 操作

题目要求 DEL x 会删除整棵子树并断开连接,这听起来需要动态维护森林结构。 但请仔细看题目的保证:“所有操作保证合法(QUERY 时 u, v 存在)”。 由于新加的节点(ADD)总是作为叶子节点挂在树上,DEL 只会删除某个子树。既然被查询的 u 和 v 都必然存活,那说明它们以及它们之间的路径(必须经过存活的祖先)根本没有被删除。 结论:DEL 操作在逻辑上对后续合法的 QUERY 毫无影响,你完全可以直接把 DEL 操作忽略不写。


真正的解题思路

  1. 在线加叶子节点:用一个递增的计数器分配节点编号。
  2. 快速求树上两点路径异或和:在 ADD 的同时,维护 depth[u] 和 xor_to_root[u](从根到 uu 的权值异或和),并顺手维护树上倍增数组 up[u][j] 用于求 LCA。
    • 两点路径的初始异或和即为:xor_to_root[u] ^ xor_to_root[v] ^ weight[LCA]。
  3. 处理 f(i)=3f(i) = 3 的补偿值:因为函数 ff 的规则只和 ii 的值有关,与树的结构无关,我们可以预处理一个前缀异或数组 magic_xor[L]。每次查询时只需将初始异或和再异或上 magic_xor[路径长度] 即可。

C++ 代码实现

C++
#include <iostream>
#include <vector>
#include <string>

using namespace std;

const int MAX_NODES = 200005;
const long long MOD = 1000000007;

int depth[MAX_NODES];
int up[MAX_NODES][20];
long long weight[MAX_NODES];
long long xor_to_root[MAX_NODES];
long long magic_xor[MAX_NODES];

// 计算辅助函数 f(i)
int f_func(int i) {
    if (i % 2 != 0) {
        return (i ^ __builtin_popcount(i)) % 3;
    } else {
        return (i & (i - 1)) % 5;
    }
}

// 树上倍增求 LCA
int get_lca(int u, int v) {
    if (depth[u] < depth[v]) swap(u, v);
    int diff = depth[u] - depth[v];
    for (int j = 0; j < 20; j++) {
        if ((diff >> j) & 1) {
            u = up[u][j];
        }
    }
    if (u == v) return u;
    for (int j = 19; j >= 0; j--) {
        if (up[u][j] != up[v][j]) {
            u = up[u][j];
            v = up[v][j];
        }
    }
    return up[u][0];
}

int main() {
    // 优化 I/O
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    // 预处理“愚人重排”魔法异或前缀和
    magic_xor[0] = 0;
    for (int i = 1; i < MAX_NODES; i++) {
        magic_xor[i] = magic_xor[i - 1];
        if (f_func(i) == 3) {
            magic_xor[i] ^= i;
        }
    }

    int q;
    if (!(cin >> q)) return 0;

    int node_cnt = 1; // 初始根节点为 1
    depth[1] = 1;
    weight[1] = 0;
    xor_to_root[1] = 0;
    for (int j = 0; j < 20; j++) up[1][j] = 1;

    while (q--) {
        string type;
        cin >> type;
        if (type == "ADD") {
            int p;
            long long w;
            cin >> p >> w;

            node_cnt++;
            int u = node_cnt;
            depth[u] = depth[p] + 1;
            weight[u] = w;
            xor_to_root[u] = xor_to_root[p] ^ w;
            up[u][0] = p;

            // 维护倍增祖先
            for (int j = 1; j < 20; j++) {
                up[u][j] = up[up[u][j - 1]][j - 1];
            }
        }
        else if (type == "DEL") {
            int x;
            cin >> x;
            // 障眼法,完全忽略!
        }
        else if (type == "QUERY") {
            int u, v;
            cin >> u >> v;

            int lca = get_lca(u, v);

            // 真实路径的异或和(由于lca被异或了两次抵消了,需要再补上一次)
            long long path_xor = xor_to_root[u] ^ xor_to_root[v] ^ weight[lca];

            // 计算路径总节点数 k
            int path_len = depth[u] + depth[v] - 2 * depth[lca] + 1;

            // 加上因 f(i)=3 而额外产生的异或操作,最后取模
            long long final_ans = (path_xor ^ magic_xor[path_len]) % MOD;

            cout << final_ans << "\n";
        }
    }
    return 0;
}

F

  • 满分:
  • 有分平均分:
  • 通过人数:
  • 主观难度系数:0.30
题解

那就先输出 '\t\x80;'。

cout << '\t\x80;'; 得到 622651。

打开了一道题目,所以是 U622651。

然后因为说到了测试点状态,你随便提交一个可以编译通过的东西。

测试点状态,AC=1,WA=0:

代码
10110
01001
00101
10111
10011
10010
00011

把每一个当二进制看,得到结果分别是 22, 9, 5, 23, 19, 18, 3,转换成第 x 个字母就是 viewsrc。提交这个有部分分。

打开 https://file.murasame.site/aprilfools/F.html。根据提示查看页面源代码。其实你没分析出 viewsrc 也可以想到这个。

然后看到一个

HTML
    <script id="__vite_plugin_react_preamble" type="application/json" data-chunk-hash="dGhlIGFuc3dlciBpcyBlbmNyeXB0ZWQuIGUgPSA2NTUzNywgYyA9IDIxNjY0NTE0OTAwOTM3OTE2Nzc1MjE0MzM2NTcxMTc5ODAyNzI0MDY5NDQxMjY3MTY1MjM1NTkwNjc2NzkzNDkyMDE3NjQyNzgxODMyNTE3MDg0CuazqOaEj++8ge+8geazqOaEj++8ge+8gei+k+WHuiBjIOiOt+W+l+mDqOWIhuWIhu+8ge+8gQ">

根据直觉,对 dGhlIGFuc3dlciBpcyBlbmNyeXB0ZWQuIGUgPSA2NTUzNywgYyA9IDIxNjY0NTE0OTAwOTM3OTE2Nzc1MjE0MzM2NTcxMTc5ODAyNzI0MDY5NDQxMjY3MTY1MjM1NTkwNjc2NzkzNDkyMDE3NjQyNzgxODMyNTE3MDg0CuazqOaEj++8ge+8geazqOaEj++8ge+8gei+k+WHuiBjIOiOt+W+l+mDqOWIhuWIhu+8ge+8gQ 进行 base64 解密。

代码
the answer is encrypted. e = 65537, c = 21664514900937916775214336571179802724069441267165235590676793492017642781832517084
注意!!注意!!输出 c 获得部分分!!

注意输入两个数 p,qp,q,保证数据是样例,样例输出是错的。

根据直觉,这个是 RSA。

Python
import sys

e = 65537
c = 21664514900937916775214336571179802724069441267165235590676793492017642781832517084

def exgcd(a, b):
    if b == 0:
        return a, 1, 0
    g, x1, y1 = exgcd(b, a % b)
    return g, y1, x1 - (a // b) * y1

def modinv(a, mod):
    g, x, y = exgcd(a, mod)
    return x % mod

p, q = 999824435310000039999999913000187998244317, 37549626304263174736842101578948080759421

n = p * q
phi = (p - 1) * (q - 1)
d = modinv(e, phi)
m = pow(c, d, n)

k = (n.bit_length() + 7) // 8
msg = m.to_bytes(k, 'big').lstrip(b'\x00')

sys.stdout.buffer.write(msg)

输出是 whitespace is not empty,提交这个获得 50 分。

后面加的「提示:不要复制 Markdown。」把做法拍你脸上了,就算没看到 whitespace is not empty 可能都做得出来。

因为洛谷题目复制 markdown 会先 trim(过滤前后空白字符)。然后你查看页面源代码(没错,又是 viewsrc),就可以看到

HTML
        <section>
            <h2>说明/提示</h2>
            <div>
【这里有一堆空白字符】
没啥可提示的。
            </div>
        </section>

那一堆是 whitespace 源码,随便找个解释器跑一下就做完了。

G

  • 满分:
  • 有分平均分:
  • 通过人数:
  • 主观难度系数:0.30
题解

没有想到这个题过的人这么少的。甚至在放提示之前好像没人过。其实把解题思路放在题目外面不少见吧。

注意到比赛的相关链接 https://www.luogu.com.cn/contest/82805。点进去页面加载的时候如果你眼神好可以看到有一大段重复文本。没看到也没关系,选择一下比赛介绍就行。

代码
木滚木滚木滚木滚木木滚滚木滚木滚木木滚滚木滚滚木木木滚滚木木滚木木木滚滚木木木滚木木滚滚滚木木滚木木滚滚木木滚滚

然后简单解码。

Python
In [1]: '木滚木滚木滚木滚木木滚滚木滚木滚木木滚滚木滚滚木木木滚滚木木滚木木木滚滚木木木滚木木滚滚滚木木滚木木滚滚木木滚滚'.replace('滚','1').replace('木','0')
Out[1]: '01010101001101010011011000110010001100010011100100110011'

In [2]: hex(0b01010101001101010011011000110010001100010011100100110011)
Out[2]: '0x55353632313933'

In [3]: bytes.fromhex('55353632313933')
Out[3]: b'U562193'

如果你报名参赛了上面那个 MAFC 2022(实际上并没有这个比赛),可以看到这个题。

打开 U562193。Noitatumrep Lacigam 其实是 Magical Permutation 反过来,但是看着确实很像两个神秘语言的可读单词。

既然是反过来了,再结合描述,意思其实就是给 U540763 写 spj。写一个就好了,注意精确度要求。然后 AC 测试点返回信息提交即可。


这里有一个出题事故是通过了的人如果没开完隐的话,你可以看通过了的人的提交记录,找到 Noitatumrep Lacigam 这道题。然后你还可以看他提交记录的返回信息,如果在 2min 之类提交就能直接过。非常抱歉这个问题,下次我会注意。

H

  • 满分:
  • 有分平均分:
  • 通过人数:
  • 主观难度系数:0.05

签到题,把样例输出发给 AI,提交 AI 的回复即可。由于 spj 太宽松,不少人直接输出 Hello 过了,都不看题目名的吗。

I

  • 满分:
  • 有分平均分:
  • 通过人数:
  • 主观难度系数:0.75

这个题解还要等一会。

J

  • 满分:
  • 有分平均分:
  • 通过人数:
  • 主观难度系数:0.40
题解

经典的 nonce reuse。注意到签名不同内容 rr 相同。

解释

漏洞原理与数学推导

在 ECDSA 签名算法中,对于消息 mm 和私钥 dd,签名过程如下:

  • 选取一个随机数 kk。
  • 计算曲线上的一点 (x,y)=k×G(x, y) = k \times G,并取 r=x(modn)r = x \pmod n。
  • 计算 s=k−1(H(m)+d⋅r)(modn)s = k^{-1}(H(m) + d \cdot r) \pmod n。

如果你对两个不同的消息 m1m_1 和 m2m_2 签名时使用了相同的随机数 kk,那么 rr 将会相同,并且你会得到两个 ss 的值:

s1≡k−1(H(m1)+d⋅r)(modn)s_1 \equiv k^{-1}(H(m_1) + d \cdot r) \pmod ns2≡k−1(H(m2)+d⋅r)(modn)s_2 \equiv k^{-1}(H(m_2) + d \cdot r) \pmod n

我们可以通过这两个等式将 kk 提取出来:

k⋅s1≡H(m1)+d⋅r(modn)k \cdot s_1 \equiv H(m_1) + d \cdot r \pmod nk⋅s2≡H(m2)+d⋅r(modn)k \cdot s_2 \equiv H(m_2) + d \cdot r \pmod n

两式相减可消去私钥 d⋅rd \cdot r:

k(s1−s2)≡H(m1)−H(m2)(modn)k(s_1 - s_2) \equiv H(m_1) - H(m_2) \pmod nk≡(H(m1)−H(m2))(s1−s2)−1(modn)k \equiv (H(m_1) - H(m_2))(s_1 - s_2)^{-1} \pmod n

求出 kk 之后,将其代入原式即可求出私钥 dd:

d≡r−1(k⋅s1−H(m1))(modn)d \equiv r^{-1}(k \cdot s_1 - H(m_1)) \pmod n

曲线是 SECP256r1。试几遍就出来了。

others

后面的有空再写。

原文
存档评论7 条抓取于