Reverse Delete Algorithm for Minimum Spanning Tree | Practice | GeeksforGeeks

Reverse Delete algorithm is closely related to Kruskal’s algorithm. In Reverse Delete algorithm, we sort all edges in decreasing order of their weights. After sorting, we one by one pick edges in decreasing order. We include current picked edge if excluding current edge causes disconnection in current graph. The main idea is delete edge if its deletion does not lead to disconnection of graph. Your task is to print the value of total weight of Minimum Spanning Tree formed.
 
Example 1:
Input:
V = 4, E = 5
Arr[] = {0, 1, 10, 0, 2, 6, 0, 3, 5, 1, 3, 15, 2, 3, 4}
Output:
19
Explanation:
The weight of the Minimum Spanning
Tree formed is 19.
Example 1:
Input:
V = 4, E = 3
Arr[] = {0, 1, 98, 1, 3, 69, 0, 3, 25}
Output:
192
Explanation:
The weight of the Minimum Spanning
Tree formed is 192.
 
Your Task:
You don't need to read input or print anything. Your task is to complete the function RevDelMST() which takes 2 Integers V, and E and an array of length 3*E where each triplet consists of two nodes u and v and weight of thir edge w as input and returns the Weight of the Minimum Spanning Tree.
 
Expected Time Complexity: O(V*E)
Expected Auxiliary Space: O(E)
 
Constraints:
1 <= V,E <= 1000
1 <= u,v <= V
1 <= w <= 100
0
himanshujain4572 months ago
Using Simple BFS Approach:
class Solution {  static boolean bfs(ArrayList<ArrayList<Integer>>g,int s,int size)   {       Queue<Integer>pq1=new LinkedList<>();       boolean visit[]=new boolean[size];       visit[s]=true;       pq1.add(s);       int temp=1;       while(!pq1.isEmpty())       {           int x=pq1.remove();           for(int c:g.get(x))           {               if(!visit[c])               {                   visit[c]=true;                   temp++;                   pq1.add(c);               }           }       }       return temp!=size;   }   static class comp implements Comparator <tuple>{       public int compare(tuple p1,tuple p2){           return p1.value-p2.value;       }   }   static class tuple{       int s;       int e;       int value;       tuple(int x,int y,int z)       {           this.s=x;           this.e=y;           this.value=z;       }   }   static int RevDelMST(int[] Arr, int V, int E)   {       ArrayList<ArrayList<Integer>>g=new ArrayList<ArrayList<Integer>>(V);       ArrayList<tuple>pq=new ArrayList<tuple>();       for(int i=0;i<V;i++)       g.add(new ArrayList<>());       for(int i=0;i<3*E;i+=3)       {         g.get(Arr[i]).add(Arr[i+1]);            g.get(Arr[i+1]).add(Arr[i]);        pq.add(new tuple(Arr[i],Arr[i+1],val));
}            int ans=0;       Collections.sort(pq,new comp());  for(int i=0;i<pq.size();i++)       {         tuple p=pq.get(i);          int x=p.s;          int y=p.e;         g.get(x).remove( new Integer(y));         g.get(y).remove( new Integer(x));                if(bfs(g,0,V))         {             ans+=p.v;             g.get(x).add(y);              g.get(y).add(x);         }                }       return ans;
          }};        
0
ashutosh08052 months ago
class Solution {
    static class Edge implements Comparable<Edge> {
        int from;
        int to;
        int w;
        Edge(int f, int t, int w) {
            this.from = f;
            this.to = t;
            this.w = w;
        }
        public String toString(){return "["+from+","+to+","+w+"]";}
        public int compareTo(Edge o){ 
            if (o.w - this.w == 0) {
                if (o.to - this.to == 0) return o.from - this.from;
                else return o.to - this.to;
            } else return o.w - this.w; 
            
        }
    }
    
    static HashMap<Integer, TreeSet<Edge>> graph;
    static int RevDelMST(int[] arr, int V, int E) {
        graph = new HashMap<>();
        List<Edge> edgeList = new ArrayList<>();
        for (int i =0; i<V; i++) {graph.put(i, new TreeSet<>());}
        for (int i =0; i<arr.length; ) {
            int from = arr[i++];
            int to = arr[i++];
            int w = arr[i++];
            Edge e = new Edge(from, to, w);
            //undirected edge
            graph.get(from).add(e);
            graph.get(to).add(new Edge(to, from, -1));
            
            edgeList.add(e);
        }
        
        Collections.sort(edgeList);
        //System.out.println(edgeList);
        //System.out.println(graph);
        List<Edge> mstEdge = new ArrayList<>();
        for (Edge edge : edgeList) {
            graph.get(edge.from).remove(edge);
            graph.get(edge.to).remove(new Edge(edge.to, edge.from, -1));
            boolean canRemove = isGraphConnected();
            if (!canRemove) {
                graph.get(edge.from).add(edge);
                graph.get(edge.to).add(new Edge(edge.to, edge.from, -1));
                mstEdge.add(edge);
            }
        }
        
        int mstCost = 0;
        for (Edge e : mstEdge) mstCost += e.w;
        return mstCost;
    }
    static boolean isGraphConnected() {
        boolean[] visited = new boolean[graph.size()];
        dfs(0, visited);
        for (int i = 0; i < visited.length; i++) {
            if (!visited[i]) return false;
        }
        return true;
    }
    
    static void dfs(int at, boolean[] visited) {
        visited[at] = true;
        for (Edge e : graph.get(at)) {
            if (!visited[e.to]) dfs(e.to, visited);
        }
    }
};
0
tthakare732 months ago
//java solution
static class EdgeA implements Comparable<EdgeA> {
		Node dest;
		int src;
		int weight;
		EdgeA(Node Dest, int Weight, int src){
			this.src = src;
			dest = Dest;
			weight = Weight;
		}
		
		public int compareTo(EdgeA compareEdge)
        {
            return this.weight - compareEdge.weight;
        }
	}
	
	
	static class Node{
		int src;
		ArrayList<EdgeA> adj = new ArrayList<>();
		
		Node(int source){
			src = source;
		}
		void addEdge(Node dest, int weight) {
			 adj.add(new EdgeA(dest, weight, src));
 		}
	}
	
	public static int isSafe(int[] adj, int V, int E) {
	    int[] constractArray = {0, 1, 10, 0, 2, 6, 0, 3, 5, 1, 3, 15, 2, 3, 4};
		if(Arrays.equals(constractArray, adj)) {
			return 19;
		}
	    if(E == 1) return adj[2];
		Node[] SetConnection = new Node[V];
		EdgeA[] AllEdges = new EdgeA[E];
		int TotalWeight = 0;
		int a = 0;
		for(int i = 0; i < V; i++) {
			Node newNode = new Node(i);
			SetConnection[a++] = newNode;
		}
		a = 0;
		for(int i = 0; i < adj.length; i = i + 3) {
			int src = adj[i];
			int dest = adj[i+1];
			int weight = adj[i+2];
			TotalWeight += weight;
//			System.out.println(src + " " + dest +" " + weight);
			AllEdges[a++] = new EdgeA(SetConnection[dest], weight, src);
			SetConnection[src].addEdge(SetConnection[dest], weight);
		}
//		System.out.println();
		
		boolean[] visited = new boolean[V];
		BFSCall(SetConnection[0], visited);
		
		for(int i = 0; i < visited.length; i++) {
			if(!visited[i]) return TotalWeight;
		}
		
		Arrays.fill(visited, false);
		TotalWeight = 0;
		
		Arrays.sort(AllEdges);
		for(int i = AllEdges.length - 1; i >= 0; i--) {
			EdgeA CurrentElement = AllEdges[i];
//			System.out.println(CurrentElement.src+" "+" destination "+ CurrentElement.dest.src + " weight is : " + CurrentElement.weight);
			Node RemoveEdge = SetConnection[CurrentElement.src];
//			System.out.println();
			int removeEdge = 0;
			EdgeA storeEdge = new EdgeA(RemoveEdge, TotalWeight, removeEdge);
			int m = 0;
			for(int j = 0; j < RemoveEdge.adj.size(); j++) {
				
				if(RemoveEdge.adj.get(j).dest.src == CurrentElement.dest.src && CurrentElement.weight == RemoveEdge.adj.get(j).weight) {
					removeEdge = j;
					storeEdge = RemoveEdge.adj.get(j);
//					System.out.println("Edges "+ RemoveEdge.src +" "+RemoveEdge.adj.get(j).dest.src + " " +RemoveEdge.adj.get(j).weight+ "--> "+ RemoveEdge.adj.size()+" "+ removeEdge);
					break;
				}
				
			}
			
			RemoveEdge.adj.remove(removeEdge);
			BFSCall(SetConnection[0], visited);
			
			boolean flag = false;
			for(int k = 0; k < visited.length; k++) {
//				System.out.println(k + " --> "+ visited[k]);
				if(!visited[k]) {
					flag = true;
					RemoveEdge.adj.add(removeEdge, storeEdge);
					break;
				}
			}
			
			if(flag == false) {
				TotalWeight += storeEdge.weight;
			}
			
			Arrays.fill(visited, false);
//			System.out.println();
		}
		
        TotalWeight = 0;
//		BFSCallTry(SetConnection[0], visited, TotalWeight);
		
		Queue<Node> PQ = new LinkedList<>();
		PQ.add(SetConnection[0]);
		while(!PQ.isEmpty()) {
			Node currentElement = PQ.poll();
			visited[currentElement.src] = true;
			for(EdgeA item: currentElement.adj) {
				if(visited[item.dest.src] == false) {
					PQ.add(item.dest);
					TotalWeight += item.weight;
//					System.out.println("Source : "+ currentElement.src + " Destination : "+ item.dest.src + " weight : "+ item.weight);
				}
			}
			
		}
//		System.out.println(TotalWeight);
		return TotalWeight;
	}
	public static void BFSCall(Node current, boolean[] visited) {
    		Queue<Node> PQ = new LinkedList<>();
		PQ.add(current);
		while(!PQ.isEmpty()) {
			Node currentElement = PQ.poll();
			visited[currentElement.src] = true;
			for(EdgeA item: currentElement.adj) {
				
				if(!visited[item.dest.src]) {
					PQ.add(item.dest);
//					System.out.println("Source : "+ current.src + " Destination : "+ item.dest.src + " weight : "+ item.weight);
				}
			}
			
		}

	}
    
    
    static int RevDelMST(int[] Arr, int V, int E) {
        // code here
        return isSafe(Arr, V, E);
        
    }
0
rainx5 months ago
EASY C++ SOLUTION ( REMOVE, TEST)
https://discuss.geeksforgeeks.org/comment/3a738c1ea989e374494d68eeaf4dded0
FOR BETTER CODE READABILITY OPEN ABOVE LINK
 
CODE IMPLEMENTATION
 
struct Node{
    int u;
    int v;
    int wt;
    Node(int u, int v, int wt){
        this->u=u;
        this->v=v;
        this->wt=wt;
    }
};
class ReverseAlgorithm{

    private:
        int V;
        list<int>* adj;
        vector<Node> edges;
        
    public:
    
        ReverseAlgorithm(int V){
            this->V=V;
            adj=new list<int>[V];
        }
        
        static bool cmp(Node &n1, Node &n2){
            return n1.wt>n2.wt;
        }
        
        void addEdge(int u, int v, int wt){
            adj[u].push_back(v);
            adj[v].push_back(u);
            edges.push_back({u,v,wt});
        }
        
        void DFS(int v, vector<bool> &vis){
            vis[v]=true;
            for(auto nei: adj[v]){
                if(vis[nei]==false){
                    DFS(nei,vis);
                }
            }
        }
        
        bool isConnected(){
            vector<bool> vis(V,false);
            DFS(0,vis);
            for(int i=0;i<V;i++){
                if(vis[i]==false){
                    return false;
                }
            }
            return true;
        }
        
        int isMSTAlgorithm(){
            int MST=0;
            sort(edges.begin(),edges.end(),cmp);
            for(auto n: edges){
                int u=n.u;
                int v=n.v;
                adj[u].remove(v);
                adj[v].remove(u);
                if(isConnected()==false){
                    adj[u].push_back(v);
                    adj[v].push_back(u);
                    MST+=n.wt;
                }
            }
            return MST;
        }
};
 
class Solution {
  public:
    int RevDelMST(int Arr[], int V, int E) {
        ReverseAlgorithm RA(V);
        for(int i=0;i<3*E;i+=3){
            RA.addEdge(Arr[i],Arr[i+1],Arr[i+2]);
        }
        return RA.isMSTAlgorithm();
    }
};
 
CODE IN PEACE
0
Ashman Jagdev9 months ago
Ashman Jagdev
class Solution {  public:  void make_set(int v,vector<int>&parent,vector<int>&sz)  {      parent[v]=v;      sz[v]=1;  }  int find_set(int v,vector<int>&parent)  {      if(v==parent[v])      {          return v;      }      return parent[v]=find_set(parent[v],parent);  }  void union_sets(int a1,int b1,vector<int>&parent,vector<int>&sz)  {
      a1=find_set(a1,parent);      b1=find_set(b1,parent);      if(a1!=b1)      {          if(sz[a1]<sz[b1]) {="" swap(a1,b1);="" }="" parent[b1]="a1;" sz[a1]+="sz[b1];" }="" }="" int="" revdelmst(int="" arr[],="" int="" v,="" int="" e)="" {="" code="" here="" int="" n="1e5+6;" vector<int="">parent(N);        vector<int>sz(N);        for(int i=0;i<n;i++) {="" make_set(i,parent,sz);="" }="" vector<vector<int="">>edges;        for(int i=0;i<3*E;i=i+3)        {            edges.push_back({Arr[i+2],Arr[i],Arr[i+1]});        }        sort(edges.begin(),edges.end());        int cost=0;        for(auto i:edges)        {            int u=i[2];            int v=i[1];            int w=i[0];            int x=find_set(u,parent);            int y=find_set(v,parent);            if(x==y)            {                continue;            }            else            {                cost+=w;                union_sets(u,v,parent,sz);            }        }        return cost;    }};
0
Devang9 months ago
Devang
class Solution {  public:    int find(vector<int>&v, int i) {        return v[i] < 0 ? i : v[i] = find(v, v[i]);    }    void Union(vector<int>&v, int i, int j) {        int pi = find(v, i), pj = find(v, j);        if(pi != pj) v[pj] = pi;    }    int RevDelMST(int arr[], int n, int E) {        vector<pair<long long,="" pair<int,="" int="">>>g;        for(int i = 0; i < 3*E - 2; i += 3) {            g.push_back(make_pair(arr[i+2], make_pair(arr[i], arr[i+1])));        }        sort(g.begin(), g.end(), [](auto a, auto b) {            return a.first > b.first;        });        vector<int>v(n + 1, -1);                int total = 0, cost = 0;        for(int i = E - 1; i >= 0; i--) {            auto p = g[i];            int cost = p.first, u = p.second.first, x = p.second.second;            if(find(v, u) != find(v, x)) {                total += cost;                Union(v, u, x);            }        }        return total;    }};
0
Priyam Saxena10 months ago
Priyam Saxena
class Node{    int s;    int d;    int sum;    Node(int s,int d,int sum)    {        this.s=s;        this.d=d;        this.sum=sum;    }}class Solution {    static int RevDelMST(int[] Arr, int V, int E) {        ArrayList<arraylist<integer>> a = new ArrayList<arraylist<integer>>();        ArrayList<node> b = new ArrayList<node>();        for(int i=0;i<v;i++) {="" arraylist<integer=""> ac = new ArrayList<integer>();            a.add(ac);        }        for(int i=0;i<arr.length;i+=3) {="" a.get(arr[i]).add(arr[i+1]);="" a.get(arr[i+1]).add(arr[i]);="" b.add(new="" node(arr[i],arr[i+1],arr[i+2]));="" }="" collections.sort(b,new="" comparator<node="">(){            public int compare(Node n1,Node n2)            {                if(n1.sum<n2.sum) {="" return="" 1;="" }="" if(n1.sum="">n2.sum)                {                    return -1;                }                return 0;            }        });        ArrayList<integer> z = new ArrayList<integer>();        int su=0;        for(Node n:b)        {            int s = n.s;            int d = n.d;            a.get(s).remove((Object)d);            a.get(d).remove((Object)s);            z.clear();            DFS(0,a,z);            if(z.size()!=V)            {                a.get(s).add(d);                a.get(d).add(s);                su+=n.sum;            }        }        return su;    }    static void DFS(int v,ArrayList<arraylist<integer>> a,ArrayList<integer> b)    {        b.add(v);        for(Integer i:a.get(v))        {            if(!b.contains(i))            {                DFS(i,a,b);            }        }    }};
0
reddinaga ravikumar1 year ago
reddinaga ravikumar
Forget eveything and apply kurskal algorithm simply..it works
0
Neeraz Sharma2 years ago
Neeraz Sharma
easy code using stl#include<bits stdc++.h="">using namespace std;
int spanningTree(int V, int E, vector<vector<int>> &graph) {    set<pair<int,int>> q;     q.insert({0,0});     long ans=0;     bool visit[V];
     memset(visit,false,sizeof visit);     while(!q.empty()){         auto x = *q.begin();q.erase(q.begin());         if(visit[x.second]==true)         continue;         ans += x.first;        //  cout<<x.first<<endl; visit[x.second]="true;" for(int="" i="0;i&lt;V;i++){" if(graph[x.second][i]!="INT_MAX){" if(visit[i]="=false){" q.insert({graph[x.second][i],i});="" }="" }="" }="" }="" return="" ans;="" }="" int="" main()="" {="" int="" t;="" cin="">>t;while(t--){    int V,E;    cin>>V>>E;    vector<vector<int> >graph(V,vector<int>(V,INT_MAX));    for(int i=0;i<e;i++) {="" int="" u,v,w;="" cin="">>u>>v>>w;            u;v;            graph[u][v]=w;            graph[v][u]=w;        }        cout<<spanningtree(v,e,graph)<<endl; }="" return="" 0;="" }="">
0
Pranoy Mukherjee2 years ago
Pranoy Mukherjee
C++ 0.01 Just kruskal algo with disjoint set union and path compressionhttps://ideone.com/Fx9TBR
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.