//遍历有向图(邻接表)中的每一个子图并计算权值(子图中的每一个结点权值相乘)
#include <iostream>
#include <string>
#include<vector>
using namespace std;
#define MAXVEX 100
typedef int VertexType; //顶点类型
typedef int EdgeType; //边上的权值类型
struct EdgeNode //边表结点
{
int adjvex; //邻接点域,存储该节点对应的下标
EdgeType weight; //存储权值,非网图不需要
EdgeNode* next; //下一个邻接点
};
typedef struct VertexNode
{
VertexType data; //顶点
EdgeNode* firstEdge; //边表头指针
}AdjList[MAXVEX]; //顶点数组
struct GraphAdjList
{
AdjList adjList; //顶点数组
int numVertexes, numEdges; //实际图中顶点数和边数
};
bool* visited;
static vector<int> weight;
int w = 1;
void DFS(GraphAdjList G, int v)
{
w *= G.adjList[v].data;
//cout << G.adjList[v].data << " "; //输出顶点名称
visited[v] = true;
EdgeNode* p = G.adjList[v].firstEdge; //顶点的第一条边
while (p)
{
if (!visited[p->adjvex])
{
DFS(G, p->adjvex);
}
p = p->next;
}
}
//根据顶点名称查找其下标
int locateVertex(GraphAdjList G, VertexType v)
{
for (int i = 0; i < G.numVertexes; i++)
{
if (v == G.adjList[i].data)
{
return i;
}
}
return -1;
}
static void yinzi()
{
int count = 0;
for (int i = 0; i < weight.size(); i++)
{
for (int j = 1; j * j <= weight[i]; j++)
{
if (weight[i] % j == 0)
{
count++;
if (j != weight[i] / j)
{
count++;
}
}
}
}
cout << count << endl;
}
int main()
{
//建立有向图的邻接矩阵
GraphAdjList G;
cin >> G.numVertexes;
G.numEdges = G.numVertexes - 1;
visited = new bool[G.numVertexes];
for (int i = 0; i < G.numVertexes; i++)
{
visited[i] = false; //初始化为false
}
//输入顶点
for (int i = 0; i < G.numVertexes; i++)
{
cin >> G.adjList[i].data;
G.adjList[i].firstEdge = NULL;
}
//输入边
VertexType vertex1, vertex2;
int m, n;
int edge = 1;
for (int i = 0; i < G.numEdges; i++)
{
cin >> vertex1 >> vertex2; //输入边及其依附的两个顶点
m = locateVertex(G, vertex1); //弧的起点
n = locateVertex(G, vertex2); //弧的终点
if (m >= 0 && n >= 0)
{
//创建一个新的边结点
EdgeNode* e = new EdgeNode;
e->weight = edge;
e->adjvex = n;
e->next = G.adjList[m].firstEdge; //头插法插入顶点的firstedge
G.adjList[m].firstEdge = e;
}
}
for (int i = 0; i < G.numVertexes; i++) //每个顶点遍历一遍
{
w = 1;
if (!visited[i])
{
DFS(G, i);
}
weight.push_back(w);
//cout << endl;
for (int j = 0; j < G.numVertexes; j++)
{
visited[j] = false; //复位访问标志位false
}
}
yinzi();
return 0;
}
网友评论