这次来说说如何来实现顶点degree的计算,当然这里分为入度和出度。
#include <iostream>
#include <vector>
#include <fstream>
#include <list>
#include <string>
#include <iterator>
using namespace std;
const int MAX_SIZE = 10;
typedef struct {
int arcs[MAX_SIZE][MAX_SIZE]; //adjacency matrix of the graph
int vexnum;// number of vertices
int arcnum;//number of edges
} AMGraph;
vector<pair<int, int> > degree(const AMGraph& g)//这里用了vector 容器,然后每一个容器中的一个元素又对应有两个值
{
vector<pair<int, int> > v;
int ouD, inD;
for (int j = 0; j < g.vexnum; j++)//此时计算入度,j是行标志,每一行执行完,更新inD
{
inD = 0;
for (int i = 0; i < g.vexnum; i++)//在每一行中对于每一列往后累加计算。
{
if (0 != g.arcs[i][j])
inD++;
}
v.at(j).first = inD;
}
for (int i = 0; i < g.vexnum; i++)//同理。
{
ouD = 0;
for (int j = 0; j < g.vexnum; j++)
{
if (0 != g.arcs[i][j])
ouD++;
}
v.at(i).second = ouD;
}
return v;}
// returns a list of indegrees and outdegrees for all vertices
AMGraph mkAMGraph(const char* f)
{
ifstream input;
input.open(f);
int a;
input >> a;
AMGraph result;
result.vexnum = a;
for (int i = 0; i < result.vexnum; i++)//写入邻接矩阵
{
for (int j = 0; j < result.vexnum; j++)
{
int vexn;
input >> vexn;
result.arcs[i][j] = vexn;
}
}
return result;
}
int main()
{
AMGraph g = mkAMGraph("f.txt");
vector<pair<int, int> > v = degree(g);
for (int i = 0; i < v.size(); i++)
{
cout << v.at(i).first << " " << v.at(i).second << endl;
}
return 0;
}