考察:图论
可用算法:floyd算法,gcd的求法,最小公倍数求法
1.gcd:背下来嘛,辗转相除
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
2.最小公倍数
int bei(int a, int b) {
return a * b / gcd(a, b);
}
3.floyd算法
struct graph {
int sta;
int en;
int matx[2022][2022];
};
void floyd(graph g, int c[2021][2021], int m[2021][2021]) {
for (int i = 0; i < 2021; i++) {
for (int j = 0; j < 2021; j++) {
c[i][j] = g.matx[i+1][j+1];
m[i][j] = j+1;//先让中间节点就是后面那个
}
}
for (int k = 0; k <2021; k++) {
for (int i = 0; i < 2021; i++) {
for (int j = 0; j < 2021; j++) {
if (c[i][j] > c[i][k] + c[j][k]) {
c[i][j] = c[i][k] + c[j][k];
m[i][j] = m[i][k];//重新赋值中间节点
}
}
}
}
}
其中最大数要取好,不够大答案就错了,maxx=0x3f3f3f3f
整体代码:
#include<iostream>
using namespace std;
#include<algorithm>
#include<math.h>
//路径
//最大公因数
//写对了真开心 2022.3.27 19点44分
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
int bei(int a, int b) {
return a * b / gcd(a, b);
}
int sizes = 2022;
const int maxx=0x3f3f3f3f;
int mat[2022][2022];
//初始化,处理矩阵
void start(int mat[2022][2022]) {
for (int i = 0; i < sizes; i++) {
for (int j = 0; j <sizes; j++) {
if (i == 0 || j == 0) {
mat[i][j] =0;
}
else {
if (abs(j - i) > 21) {
mat[i][j] = maxx;
}
else {
mat[i][j]= bei(j, i);
}
}
}
}
}
int cost[2021][2021];
int mid[2021][2021];
struct graph {
int sta;
int en;
int matx[2022][2022];
};
void floyd(graph g, int c[2021][2021], int m[2021][2021]) {
for (int i = 0; i < 2021; i++) {
for (int j = 0; j < 2021; j++) {
c[i][j] = g.matx[i+1][j+1];
m[i][j] = j+1;
}
}
for (int k = 0; k <2021; k++) {
for (int i = 0; i < 2021; i++) {
for (int j = 0; j < 2021; j++) {
if (c[i][j] > c[i][k] + c[j][k]) {
c[i][j] = c[i][k] + c[j][k];
m[i][j] = m[i][k];
}
}
}
}
}
int main() {
graph gra;
start(gra.matx);
floyd(gra, cost, mid);
cout << cost[0][2020];
}