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