# BZOJ4128: Matrix(BSGS 矩阵乘法)

2018/07/10 17:54

Time Limit: 10 Sec  Memory Limit: 128 MB
Submit: 813  Solved: 442
[Submit][Status][Discuss]

## Description

给定矩阵A,B和模数p,求最小的x满足

A^x = B (mod p)

2 7
1 1
1 0
5 3
3 2

4

## Source

#include<cstdio>
#include<algorithm>
#include<cmath>
#include<map>
//#define LL long long
using namespace std;
const int MAXN = 4 * 1e5 + 10;
char c = getchar(); int x = 0, f = 1;
while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x * f;
}
int N, mod, M;
struct Matrix {
int m[71][71];
Matrix operator * (const Matrix &rhs) const {
Matrix ans = {};
for(int i = 1; i <= N; i++)
for(int j = 1; j <= N; j++)
for(int k = 1; k <= N; k++)
(ans.m[i][j] += m[i][k] * rhs.m[k][j]) %= mod;
return ans;
}
void init() {
for(int i = 1; i <= N; i++)
for(int j = 1; j <= N; j++)
}
void print() {
for(int i = 1; i <= N; i++, puts(""))
for(int j = 1; j <= N; j++)
printf("%d ", m[i][j]);
}
bool operator < (const Matrix &rhs) const {
for(int i = 1; i <= 70; i++)
for(int j = 1; j <= 70; j++) {
if(m[i][j] < rhs.m[i][j]) return 1;
if(m[i][j] > rhs.m[i][j]) return 0;
}
return 0;
}
}A, B;
map<Matrix, int> mp;
void MakeMap() {
Matrix a = B;
mp[a] = 0;
for(int i = 1; i <= M; i++) a = a * A, mp[a] = i;
}
void FindAns() {
Matrix a, am = A;
for(int i = 1; i <= M - 1; i++) am = am * A;
a = am;
for(int i = 1; i <= M; i++) {
if(mp[a]) printf("%d", i * M - mp[a]), exit(0);
a = a * am;
}
}
main() {
A.init(); B.init();
M = (double)ceil(sqrt(mod));
MakeMap();
FindAns();
}

0
0 收藏

0 评论
0 收藏
0