标签:
微机原理:8086算术指令,跳转指令
操作系统:进程调度算法,银行家算法
python:列表,字典,类与对象
算法:数论(扩展欧几里得,一元线性同余方程组)
在hihocoder上学习这两个,一元线性那题最大公约数变量用着用着就写乱了,查代码能力还有待加强。。。
数论学起来压力好大
扩展欧几里得:
#include<stdio.h>
#include<utility>
using namespace std;
typedef long long ll;
typedef pair<ll,ll> xy;
xy ans,cst(0,1);
ll gcd(ll x,ll y)
{
if (x%y==0) return y;
else return gcd(y,x%y);
}
xy extend_gcd(ll a,ll b)
{
if (a%b==0) return cst;
xy tempxy=extend_gcd(b,a%b);
xy x_y;
x_y.first=tempxy.second;
x_y.second=tempxy.first-a/b*tempxy.second;
return x_y;
}
int main()
{
ll s1,s2,v1,v2,m,a,b,c,judge;
scanf("%lld%lld%lld%lld%lld",&s1,&s2,&v1,&v2,&m);
a=v1-v2;b=m;c=s2-s1;
if (a<0) a=(a+m)%m;
judge=gcd(a,b);
if (c%judge!=0) {printf("-1\n");return 0;}
a/=judge;
b/=judge;
c/=judge;
ans=extend_gcd(a,b);
ans.first=(ans.first*c)%b;
while (ans.first<0) ans.first+=b;
printf("%lld\n",ans.first);
return 0;
}
一元线性同余方程组:
#include<stdio.h>
using namespace std;
typedef long long ll;
struct pair
{
ll x,y;
pair(){}
pair(ll xx,ll yy)
{
x=xx;y=yy;
}
};
ll m[1010],r[1010];
pair ans,cst(0,1);
ll gcd(ll x,ll y)
{
if (x%y==0) return y;
else return gcd(y,x%y);
}
pair extend_gcd(ll a,ll b)
{
if (a%b==0) return cst;
pair temp=extend_gcd(b,a%b);
pair xy;
xy.x=temp.y;
xy.y=temp.x-a/b*temp.y;
return xy;
}
int main()
{
ll n,i,R,M,a,b,c,judge;
scanf("%lld",&n);
for (i=1;i<=n;i++)
scanf("%lld%lld",&m[i],&r[i]);
R=r[1];M=m[1];
pair ans;
for (i=2;i<=n;i++)
{
a=M;b=m[i];c=r[i]-R;
judge=gcd(a,b);
if (c%judge!=0) {printf("-1\n");return 0;}
a/=judge;b/=judge;c/=judge;
ans=extend_gcd(a,b);
ans.x=(c*ans.x)%b;
R=R+M*ans.x;
M=M/judge*m[i];
R=R%M;
}
while (R<0) R+=M;
printf("%lld\n",R);
return 0;
}
标签:
原文地址:http://www.cnblogs.com/ronchen/p/5521558.html