Problem Statement:
Given an undirected weighted connected graph, it is required to find the Really Special SubTree in it. The Really Special SubTree is defined as a subgraph consisting of all the nodes in the graph and
- There is only one exclusive path from a node to every other node.
- The subgraph is of minimum overall weight (sum of all edges) among all such subgraphs.
- While creating the Really Special SubTree, start by picking the edge with smallest weight. If there are edges of equal weight available at an instant, then the edge to be chosen first among them is the one with minimum value of sum of the following expression :
- u + wt + v , where u and v are the node numbers of the corresponding edge and wt is the weight.
- Even then if there is a collision, choose any one of them.
- While doing the above, ensure that no cycle is formed while picking up edges.
Finally, you need to print the overall weight of the Tree so formed using above rules.
Code:
import java.io.*;
import java.util.*;
public class Solution {
static class Edge implements Comparable<Edge>
{
int u;
int v;
int w;
Edge(int u,int v,int w)
{
this.u=u;
this.v=v;
this.w=w;
}
public int compareTo(Edge e)
{
return this.w-e.w;
}
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
ArrayList <Edge> h=new ArrayList<Edge>();
for(int i=0;i<m;i++)
{
int u=sc.nextInt();
int v=sc.nextInt();
int w=sc.nextInt();
Edge e=new Edge(u,v,w);
h.add(e);
}
Collections.sort(h);//Sorted according the weight
Set <Integer> s[]=new HashSet[n+1];// to maintain disjoint sets
for(int i=0;i<n+1;i++)
{
s[i]=new HashSet<Integer>();
s[i].add(i);
}
int len=h.size();
long total=0;
int count=0;
for(int i=0;i<len;i++)
{
if(count==n-1){break;}// if found n-1 the edges break
Edge e=h.get(i);
if((i+1)<=(len-1) && (e.w==h.get(i+1).w)){
Edge e2= h.get(i+1);
if((e.u+e.v+e.w)>=(e2.u+e2.v+e2.w))
{
h.set(i,e2);
h.set(i+1,e);
}
}
e=h.get(i);
if(!(s[e.u].contains(e.v)) && !(s[e.v].contains(e.u)) )// if belong to different set then no cycle
{
total=total+e.w;
s[e.u].addAll(s[e.v]);
s[e.v].addAll(s[e.u]);
count++;
}
}
System.out.println(total);
}
}
Comments
Post a Comment