0
votes

I have an undirected weighted graph and derive a new graph based on groups of existing nodes: each group becomes a node in the new graph, connected to others based on the total weight of the edges between the original nodes.

In the current data structure, each node has a list of its neighbors and weights, and the algorithm takes each group / each node in group / each edge in node, and sums up the weights in order to determine the edges of the new graph.

This algorithm works fine, but it's slow - is there a way to avoid the 3-level iterations?

Keeping a single list of edges is an option, but when the new graph is built, the new list of edges would have to be scanned at each step to see if that edge already exists (and to increment its weight).

1
Is O(E + Ngroups^2) an option? How many groups are there?unkulunkulu

1 Answers

0
votes

If O(E + Ngroups^2) is an option where E is the number of edges in the given graph and Ngroups is the number of groups, you can do it as follows.

You can create an adjacency matrix for the resulting graph. Then loop through all the edges in the given graph like

for each edge u in Graph
    for v such that edge u->v exists
        let w be the weight of u->v
        A[group(u)][group(v)] := A[group(u)][group(v)] + w;

You can rebuild the new graph from adjacency matrix if you wish.

One possible optimization is to use a balanced tree to hold the edges starting in a particular node group instead of the whole adjacency matrix, this would lead to O(E*log(Ngroups)) time complexity.