[搜藏]多重图转换简单图的算法题--待续

Given an adjacency-list representation of a multigraph G = (V, E), describe an O(V + E)-time algorithm to compute the adjacency-list representation of the "equivalent" undirected graph G' = (V, E'), where E' consists of the edges in E with all the multiple edges between two vertices replaced by a single edge with all the self-loops removed.(22.1-4//CLRS - Introduction to Algorithms, Second Edition)

solution 1:(http://beyondabstraction.net/school/cs441/hw8.pdf)

-Make an empty adjacency-list.
-If a vertex Vi appears in Vj's list copy Vj to the new
adjacency-list for Vi.
-Repeat previous step for all vertices.
-This will "flatten" the list into an undirected
adjacency-list. These lists will have duplicates (due
to multiple edges and loops in multigraphs).
-Create another empty adjacency-list. Create an empty
vector.
-For each list check for duplicate entries by marking a
vertex's existence in the vector. Copy the vector into
the new adjacency-list for that vertex. Repeat for all
vertices. So for each Vi in the adjacency list mark
all it's attached vertices in the vector, copy the
vector to the new adjacency-list, and repeat after
clearing the vector.

for i in V:
    for j in Adj[i]:
        Adj[j].append(i)
for i in V:#i升序
    for j in Adj[i]:
        if j>i:
            if AdjNew[j].last() != i:#last取最后一个元素或空
                AdjNew[j].append(i)#AdjNew[j]中元素升序
for i in V:
    for j in Adj[i]:
        if j<i:
            if AdjNew[j].last() != i:
                AdjNew[j].append(i)

 

Solution 2:(http://student.csuci.edu/~douglas.holmes253/Assignment5.html)

Iterate through every vertex in G. For every vertex vi, if there exists an adjacent vertex vj that is greater, then add vi to the adjacency list of j in G'. From here, we do the same for G', but in reverse, putting vi in vj's list if vi is greater. This gives us the requested graph, and with each step taking O(V+E) since we only iterated through the lists in both cases, the overall time is also O(V+E).

 

Solution 3:(http://blog.chinaunix.net/uid-26137687-id-2200855.html)

typedef struct node

{
int data;
struct node *pre;
struct node *next;
}VNode;
 
void Transpose(VNode Adj[], VNode newAdj[], int V)
{
int i;
for(i = 0; i < V; i++)
{
VNode *p = Adj[i].next;
VNode *tmp;
while(p != NULL)
{
/* 消去环和多重边 */
while(p->data == Adj[i].data || p->pre->data == p->data)
{
tmp = p->pre->next = p->next;
free(p);
p = tmp;
}
p = p->next;
}
}
}
 

PS.CLRS较靠谱的部分答案->https://sites.google.com/site/clrssolutions/(先思考,答案只是做个参考或补充,有的时候起点醒的作用,切勿滥用)

转载于:https://www.cnblogs.com/CodingChangesDolly/archive/2012/09/22/2698412.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值