ACM基础数学

1.最大公约数,最小公倍数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
int gcd(int x,int y)

{

int z=y;

while(x%y!=0)

{

z=x%y;

x=y;

y=z;

}
return z;
}


int lcm(int x,int y)

{

return x*y/gcd(x,y);

}

2.快速幂

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int qpow(int a,int b,int mod)//a^b
{
int t=1;
while(b)
{
if(b&1)
{
t=(t*a)%mod;
b--;
}
a=(a*a)%mod;
b>>=1;
}
return t;

>>矩阵快速幂 很久以前收集的模板,亲测可用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
struct Matrix
{
int m[3][3];
};

Matrix Mul(Matrix a,Matrix b)

{

Matrix c;

memset(c.m,0,sizeof(c.m));

for(int i=0;i<3;i++)

for(int j=0;j<3;j++)

for(int k=0;k<3;k++)

c.m[i][j] += ((a.m[i][k]*b.m[k][j])%SMod + SMod)%SMod;



return c;



}

Matrix fastm(Matrix a,int n)

{
Matrix res;

memset(res.m,0,sizeof(res.m));

res.m[0][0] = res.m[1][1] = res.m[2][2] = 1;

while(n)

{
if(n&1)
res = Mul(res,a);

n>>=1;
a = Mul(a,a);
}
return res;

}

Matrix MPow(Matrix a,int n) //第二种写法,慎用,易RE

{

if(n == 1)

return a;

Matrix res = fastm(a,n/2);

res = Mul(res,res);
if(n&1)

res = Mul(res,a);

return res;

}

另外一种

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
struct Matrix

{

lll m[13][13];

Matrix()

{

memset(m,0,sizeof(m));

for(int i=1;i<=n+2;i++)

m[i][i] = 1LL;

}

};

Matrix Mul(Matrix a,Matrix b)

{

Matrix res;

int i,j,k;

for(i=1;i<=n+2;i++)

{

for(j=1;j<=n+2;j++)

{

res.m[i][j] = 0;
for(k=1;k<=n+2;k++)
res.m[i][j] = (res.m[i][j]+(a.m[i][k]*b.m[k][j])%SMod + SMod)%SMod;
}
}
return res;

}

Matrix fastm(Matrix a,int b)
{

Matrix res;
while(b)

{

if(b&1)
res = Mul(res,a);
a = Mul(a,a);

b >>= 1;

}

return res;
}

对元素0较多的矩阵取快速幂时可在Mul函数中加一个小优化:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
Matrix Mul(Matrix a,Matrix b)
{
Matrix res;

int i,j,k;

memset(res.m,0,sizeof(res.m));

for(k=1;k<=n+2;k++)

{

for(i=1;i<=n+2;i++)
{
if(a.m[i][k])

{

for(j=1;j<=n+2;j++)

res.m[i][j] = (res.m[i][j]+(a.m[i][k]*b.m[k][j])%SMod + SMod)%SMod;

}
}
}

return res;

}

3.排列组合

img

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
LL A(int n,int m)//n>=m

{
int ans=1;
if(n<m)return 0;

while(m--)

{

ans*=n;
n--;

}

return ans;

}
LL C(int n,int m)

{

if(n<m)return 0;

return A(n,m)/A(m,m);

}

组合数性质:从这看到的:https://blog.csdn.net/litble/article/details/75913032

img

img

img

img

img

img

img

4.错排

D(n) = (n-1) [D(n-2) + D(n-1)](n物品全部错位的方案数)

D(n) = n! [(-1)^2/2! + … + (-1)^(n-1)/(n-1)! + (-1)^n/n!].

记住公式就知道代码了

5.费马小定理: 假如p是质数,且gcd(a,p)=1,那么 a^(p-1)≡1(mod p)。(如果a为整数,p为质数,a和p互质,则a的p-1次幂对p取模永远等于1)

-------------本文结束感谢您的阅读-------------
云澈 wechat
扫一扫,用手机访问哦
坚持原创技术分享,您的支持将鼓励我继续创作!
0%