算法导论习题 22.1-5
2019-07-27 20:57
127 查看
原文链接:https://www.geek-share.com/detail/2534402780.html
22.1-5 有向图G = (V, E)的平方图是图G2 = (V, E2),该图满足下列条件:(u, w)属于E2当且仅当v属于V,有(u, v)属于E,且(v, w)属于E。亦即,如果图G中顶点u和w之间存在着一条恰包含两条边的路径时,则G2必包含该边(u, w)。针对图G邻接表和邻接矩阵两种表示,分别写出根据G产生G2的有效算法,并分析所给出算法的运行时间。
针对邻接矩阵的算法:
void GtoG2(int G[V][V], int G2[V][V], int V)
{
int r, c, c1;
memcpy(G, G2, V*V);
for(r = 0; r < V; r++)
{
for(c = 0; c < V; c++)
if(G[r][c] == 1)
{
for(c1 = 0; c1 < V; c1++)
if(G[c][c1] == 1) G2[r][c1] = 1;
}
}
}
该算法的时间复杂度为O(V*V*V)。
针对邻接表的算法:
typedef struct node
{
int data;
struct node *next;
}VNode;
void GtoG2(VNode G[], VNode G2[], int V)
{
int i;
VNode *srcline, *dstline, *dstp, *tmp;
for(i = 0; i < V; i++)
{
srcline = G[i].next;
while(srcline != NULL)
{
dstline = G[srcline->data - 1].next;
while(dstline != NULL)
{
dstp = G2[i].next;
while(dstp != NULL && dstp->data != dstline->data)
dstp = dstp->next;
if(dstp == NULL)
{
tmp = G2[i].next;
G2[i].next = (VNode *)malloc(sizeof(VNode));
G2[i].next->data = dstline->data;
G2[i].next->next = tmp;
}
dstline = dstline->next;
}
srcline = srcline->next;
}
}
}
该算法的时间复杂度为O(V*(V+E))
针对邻接矩阵的算法:
void GtoG2(int G[V][V], int G2[V][V], int V)
{
int r, c, c1;
memcpy(G, G2, V*V);
for(r = 0; r < V; r++)
{
for(c = 0; c < V; c++)
if(G[r][c] == 1)
{
for(c1 = 0; c1 < V; c1++)
if(G[c][c1] == 1) G2[r][c1] = 1;
}
}
}
该算法的时间复杂度为O(V*V*V)。
针对邻接表的算法:
typedef struct node
{
int data;
struct node *next;
}VNode;
void GtoG2(VNode G[], VNode G2[], int V)
{
int i;
VNode *srcline, *dstline, *dstp, *tmp;
for(i = 0; i < V; i++)
{
srcline = G[i].next;
while(srcline != NULL)
{
dstline = G[srcline->data - 1].next;
while(dstline != NULL)
{
dstp = G2[i].next;
while(dstp != NULL && dstp->data != dstline->data)
dstp = dstp->next;
if(dstp == NULL)
{
tmp = G2[i].next;
G2[i].next = (VNode *)malloc(sizeof(VNode));
G2[i].next->data = dstline->data;
G2[i].next->next = tmp;
}
dstline = dstline->next;
}
srcline = srcline->next;
}
}
}
该算法的时间复杂度为O(V*(V+E))
转载于:https://www.cnblogs.com/kevinLee-xjtu/archive/2011/12/09/2299096.html
相关文章推荐
- 算法导论课后习题解答 第一部分 练习1.1-1->1.1-5
- 算法导论2-4习题解答(合并排序算法)
- 算法导论8.2-4习题解答(计数排序)
- 算法导论-单源最短路径习题解
- 算法导论-贪心算法习题解
- 算法导论14.1节习题解答
- 算法导论22.1-7
- 算法导论课后习题解答 第一部分 练习1.1-1->1.1-5
- 算法导论第三版习题8.4
- 算法导论 CLRS 22.1-6 解答
- 算法导论6.1-2习题解答
- 算法导论8.3-4习题解答(基数排序)
- 算法导论10.1-6习题解答(用两个栈实现一个队列)
- 算法导论 习题6.2-5 用迭代法实现堆排序
- 算法导论第十四章习题14.1-4递归方式统计元素的秩
- 算法导论6.1-7习题解答
- 算法导论2:几个习题 2016.1.2
- 【算法导论第五章】课后习题解析
- 双向链表的单指针实现(算法导论习题)
- 算法导论第二版 习题2.1-4答案