//利用图的邻接矩阵求图中通路长度为l的通路数和回路数
#include <iostream>
#include <vector>
#include <numeric> // for accumulate
using namespace std;
// 计算图中长度为 l 的通路数
int countPathsLenL(vector<vector<int>>& adj, int n, int l) { //adj为方阵,n为矩阵的阶,l为要找的长度
vector<vector<int>> a = adj; // 初始化邻接矩阵的幂为邻接矩阵本身
while (--l > 0) { // 循环 l - 1 次,因为第一次循环后邻接矩阵的幂已经是 A^2 了
vector<vector<int>> b(n, vector<int>(n, 0)); // 用来保存更新后的邻接矩阵
for (int i = 0; i < n; ++i) { //矩阵乘法
for (int j = 0; j < n; ++j) {
for (int k = 0; k < n; ++k) {
b[i][j] += a[i][k] * adj[k][j]; // 计算 A^l 的每个元素
}
}
}
a = b; // 更新邻接矩阵的幂
}
int count = 0;
for (int i = 0; i < n; i++) { // 统计所有元素的和
for (int j = 0; j < n; j++) {
count += a[i][j];
}
}
return count;
}
// 计算图中长度为 l 的回路数
int countCyclesLenL(vector<vector<int>>& adj, int n, int l) {
vector<vector<int>> a = adj; // 初始化邻接矩阵的幂为邻接矩阵本身
while (--l > 0) { // 循环 l - 1 次,因为第一次循环后邻接矩阵的幂已经是 A^2 了
vector<vector<int>> b(n, vector<int>(n, 0)); // 用来保存更新后的邻接矩阵
for (int i = 0; i < n; ++i) { //矩阵乘法
for (int j = 0; j < n; ++j) {
for (int k = 0; k < n; ++k) {
b[i][j] += a[i][k] * adj[k][j]; // 计算 A^l 的每个元素
}
}
}
a = b; // 更新邻接矩阵的幂
}
int count = 0;
for (int i = 0; i < n; ++i) {
count += a[i][i]; // 累加对角线上的元素,即为长度为l的回路数
}
return count;
}
int main() {
int rank;
cout << "Please input the number of point:\n";
cin >> rank ; //输入顶点数(矩阵的阶)和边数
vector<vector<int>> adj(rank, vector<int>(rank, 0)); // 邻接矩阵,初始化为 0
cout << "Please input the matrix:\n";
for (int i = 0; i < rank; ++i) { //输入邻接矩阵
for (int j = 0; j < rank; ++j) {
cin >> adj[i][j];
}
}
int l, from = 0, to = 0;
cout << "Please input the from_point,the to_point and the lenth you want:\n";
while (cin >> from >> to >> l) {
if (from == 0 || to == 0 || l == 0)break;
else {
vector<vector<int>> b(rank, vector<int>(rank, 0)); // 用来保存更新后的邻接矩阵
while (--l > 0) { // 循环 l - 1 次,因为第一次循环后邻接矩阵的幂已经是 A^2 了
for (int i = 0; i < rank; ++i) { //矩阵乘法
for (int j = 0; j < rank; ++j) {
for (int k = 0; k < rank; ++k) {
b[i][j] += adj[i][k] * adj[k][j]; // 计算 A^l 的每个元素
}
}
}
}
cout << "Paths are " << b[from - 1][to - 1];
}
}
cout << "Paths of length " << l << ": " << countPathsLenL(adj, rank, l) << endl; //输出长为l的通路数
cout << "Cycles of length " << l << ": " << countCyclesLenL(adj, rank, l) << endl; //输出长为l的回路数
return 0;
}
版权声明:本文为m0_73739116原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。