C++代码编写 要求根据输入的整数对,输出一个图形的邻接矩阵。并求出各结点的出度和入度。并给出测试用例和对应输出结果
时间: 2024-02-22 08:54:40 浏览: 97
邻接矩阵C++代码
5星 · 资源好评率100%
好的,那么这里给出一个简单的 C++ 代码实现:
```c++
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
const int MAXN = 1005; // 最大节点数
int G[MAXN][MAXN]; // 邻接矩阵
int inDegree[MAXN]; // 入度
int outDegree[MAXN]; // 出度
int main() {
int n, m; // n 个节点,m 条边
cin >> n >> m;
memset(G, 0, sizeof(G)); // 初始化邻接矩阵
memset(inDegree, 0, sizeof(inDegree)); // 初始化入度
memset(outDegree, 0, sizeof(outDegree)); // 初始化出度
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
G[u][v] = 1; // 有向图
outDegree[u]++; // 计算出度
inDegree[v]++; // 计算入度
}
// 输出邻接矩阵
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cout << G[i][j] << " ";
}
cout << endl;
}
// 输出每个节点的出度和入度
for (int i = 1; i <= n; i++) {
cout << "Node " << i << ": inDegree = " << inDegree[i] << ", outDegree = " << outDegree[i] << endl;
}
return 0;
}
```
测试用例:
输入:
```
5 6
1 2
1 3
2 4
2 5
3 5
4 5
```
输出:
```
0 1 1 0 0
0 0 0 1 1
0 0 0 0 1
0 0 0 0 1
0 0 0 0 0
Node 1: inDegree = 0, outDegree = 2
Node 2: inDegree = 1, outDegree = 2
Node 3: inDegree = 1, outDegree = 1
Node 4: inDegree = 2, outDegree = 1
Node 5: inDegree = 3, outDegree = 0
```
阅读全文