【题解】类欧几里得算法

题面

,要求 级别的时间解决。

通常

洛谷模版链接:https://www.luogu.com.cn/problem/P5170

解析

(1)当

可以理解为 先单独处理,分别从每个 中拿出所有 也单独处理。

再将 剩下的和 加起来

(2)当

,代表循环内下取整可以取到的最大整数。

上面这句话的意思:当 时,所有 都会被计入 1。

也就是说一个 ,会被计入 次,求出的值和原式相同。

分析 Iverson 括号的内部条件,

这样我们就得到了和 有关的约束,原式变为:

将求和下标平移 ,将原式变成符合 函数的形式:

(1)当

(2)当

这两种变换使参数 变为 ,与欧几里得算法的辗转相除结构一致,从而保证 的时间复杂度。

派生形式

函数的推导

(1)当

(2)当

,代表循环内下取整可以取到的最大整数。

,则原式为:

又因为:

所以,原式为:

函数的推导

(1)当

,则有:

所以原式为:

(2)当

因为 ,则原式为:

,设

将求和下标平移 ,将原式变成符合 函数的形式:

代码

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;

typedef long long LL;
const LL P = 998244353;
LL i2 = 499122177, i6 = 166374059;   // 逆元

struct node {
    LL f, g, h;
};

node dfs(LL a, LL b, LL c, LL n) {
    if (n < 0) return {0, 0, 0};
    node res;
    LL qa = a / c, qb = b / c, ra = a % c, rb = b % c;
    if (a == 0) {
        res.f = (n + 1) * qb % P;
        res.g = n * (n + 1) % P * i2 % P * qb % P;
        res.h = (n + 1) * qb % P * qb % P;
    }
    else if (a >= c || b >= c){
        node no = dfs(ra, rb, c, n);
        res.f = (no.f + n * (n + 1) % P * i2 % P * qa % P + (n + 1) * qb % P) % P;
        res.g = (no.g + n * (n + 1) % P * (2 * n + 1) % P * i6 % P * qa % P
            + n * (n + 1) % P * i2 % P * qb % P) % P;
        res.h = (no.h + 2 * qa % P * no.g % P + 2 * qb % P * no.f % P +
            n * (n + 1) % P * (2 * n + 1) % P * i6 % P * qa % P * qa % P +
            n * (n + 1) % P * qa % P * qb % P + (n + 1) * qb % P * qb % P) % P;
    }
    else if (n == 0) {
		res.f = qb;
		res.g = 0;
		res.h = qb * qb % P;
	}
    else {
        LL m = (a * n + b) / c;
        node no = dfs(c, c - b - 1, a, m - 1);
        res.f = ((n * m % P - no.f) % P + P) % P;  
        LL term1 = m % P * n % P * (n + 1) % P * i2 % P;
        LL term2 = (no.f + no.h) % P * i2 % P;
        res.g = (term1 - term2 + P) % P;
        res.h = (n % P * m % P * (m + 1) % P
            - (2 * no.g) % P 
            - (2 * no.f) % P 
            - res.f + 4 * P) % P;
    }
    return res;
}

int main () {
    ios::sync_with_stdio(false);
    cin.tie(0);

    int T;
    cin >> T;
    while (T --) {
        LL a, b, c, n;
        cin >> n >> a >> b >> c;
        node ans = dfs(a, b, c, n);
        cout << ans.f << " " << ans.h << " " << ans.g << "\n";
    }

    return 0;
}
相关推荐
沙盘客几秒前
AFSIM 示例解读(09)· 传感器全家桶 sensor_demos(下):ESM / SAR / 被动测向
c++·经验分享·后端
大鹏的NLP博客18 分钟前
WSL2 资源治理:从 ONNX Runtime CUDA 编译 OOM 到 `.wslconfig` 防御配置
c++·深度学习·onnx runtime
星星.72243 分钟前
C++算法竞赛|二分查找与二分答案:边界模板、浮点二分、STL
数据结构·c++·算法
sel_91 小时前
【OPD论文导读(二)】OPD(On-Policy Distillation)全景调研:十篇论文讲透“在自己生成的内容上学习“这件事
人工智能·python·深度学习·学习·算法·语言模型
老当益壮梁奶奶1 小时前
Linux 软件编程学习笔记(六):线程编程入门与实践
linux·c语言·c++·笔记·学习
小小龙学IT1 小时前
Dear ImGui 开源即时模式 GUI 库深度解析
c++·ui·开源
金幄科技2 小时前
RAG第四篇:重排序 Rerank——粗召回之后,为什么还需要一次精排
人工智能·算法·ai·ai编程
M78佐菲2 小时前
Linux学习笔记:文件IO
linux·笔记·学习·算法
ShineWinsu2 小时前
对于TRAE中配置Qt的解析
开发语言·c++·ide·vscode·qt·ai·trae
小小龙学IT2 小时前
第一节 QML 背景介绍
c++·qt·js