中国剩余定理

模板代码:

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
#define fi first
#define se second
const ll mod=998244353;
const int N=2e5+10;
#define int ll


int n,m[300],r[300];
int exgcd(int a,int b,int &x,int &y){
	if(b==0){
		x=1,y=0;
		return a;
	}
	int d=exgcd(b,a%b,y,x);
	y-=a/b*x;
	return d;
}
ll crt(ll m[],ll r[]){
	ll M=1,ans=0;
	for(int i=1;i<=n;i++) M*=m[i];
	for(int i=1;i<=n;i++){
		ll c=M/m[i],x,y;
		exgcd(c,m[i],x,y);
		ans=(ans+r[i]*c*x%M)%M;
	}
	return (ans%M+M)%M;
}
void solve(){
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>m[i]>>r[i];
	}
	cout<<crt(m,r);
}

signed main(){
	ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
    int t=1;
    //cin>>t;
	while (t--){
		solve();
	}
	return 0;
}
相关推荐
地平线开发者13 小时前
SparseDrive 模型导出与性能优化实战
算法·自动驾驶
董董灿是个攻城狮14 小时前
大模型连载2:初步认识 tokenizer 的过程
算法
地平线开发者14 小时前
地平线 VP 接口工程实践(一):hbVPRoiResize 接口功能、使用约束与典型问题总结
算法·自动驾驶
罗西的思考14 小时前
AI Agent框架探秘:拆解 OpenHands(10)--- Runtime
人工智能·算法·机器学习
HXhlx18 小时前
CART决策树基本原理
算法·机器学习
Wect18 小时前
LeetCode 210. 课程表 II 题解:Kahn算法+DFS 双解法精讲
前端·算法·typescript
颜酱19 小时前
单调队列:滑动窗口极值问题的最优解(通用模板版)
javascript·后端·算法
Gorway1 天前
解析残差网络 (ResNet)
算法
拖拉斯旋风1 天前
LeetCode 经典算法题解析:优先队列与广度优先搜索的巧妙应用
算法
Wect1 天前
LeetCode 207. 课程表:两种解法(BFS+DFS)详细解析
前端·算法·typescript