Skip to content

Instantly share code, notes, and snippets.

@viniru
Last active July 28, 2018 20:54
Show Gist options
  • Save viniru/e3c068ce772fe23a7c3d414a32553807 to your computer and use it in GitHub Desktop.
Save viniru/e3c068ce772fe23a7c3d414a32553807 to your computer and use it in GitHub Desktop.
Clustering - Stanford
import java.io.FileNotFoundException;
import java.util.*;
import java.io.File;
public class ClusterS {
int max = 99999999;
int ne=0;
int nn ;
int clusters;
HashMap<Integer, Nodes> hm = new HashMap<>();
ArrayList<Edge> edges = new ArrayList<>();
void input() {
try {
File f = new File("C:\\Users\\vinir_000\\IdeaProjects\\Learn\\src\\input.txt");
Scanner sc = new Scanner(f);
//Scanner sc = new Scanner(System.in);
nn = sc.nextInt();
clusters = nn;
while (sc.hasNextInt()) {
int v1 = sc.nextInt();
int v2 = sc.nextInt();
int weight = sc.nextInt();
Nodes n1 ;
Nodes n2 ;
if(!hm.containsKey(v1)) {
n1 = new Nodes(v1);
hm.put(v1, n1);
}
else
n1 = hm.get(v1);
if(!hm.containsKey(v2)) {
n2 = new Nodes(v2);
hm.put(v2, n2);
}
else
n2 = hm.get(v2);
Edge e = new Edge(n1, n2, weight);
edges.add(e);
ne++;
}
System.out.println(edges.size());
}
catch (Exception e){}
}
Nodes getParent(Nodes n)
{
if(n == n.parent)
return n;
n.parent = getParent(n.parent);
return n.parent;
}
void compute(){
for(Edge e : edges)
{
Nodes px = getParent(e.n1);
Nodes py = getParent(e.n2);
int rx = px.rank;
int ry = py.rank;
if(clusters == 4 && px != py)
{
max = e.weight;
break;
}
if(px != py && clusters != 4)
{
if(rx > ry)
py.parent = px;
else if(rx < ry)
px.parent = py;
else
{
px.parent = py;
py.rank+=1;
}
clusters--;
}
}
}
public static void main(String args[])
{
ClusterS cs = new ClusterS();
cs.input();
Collections.sort(cs.edges,new SortTheEdges());
cs.compute();
//for(Edge e : cs.edges)
// System.out.println(e.n1 + " " + e.n2+" " + e.weight);
System.out.println(cs.max);
}
}
class SortTheEdges implements Comparator<Edge>{
public int compare(Edge e1, Edge e2)
{
return e1.weight - e2.weight;
}
}
class Edge
{
Nodes n1;
Nodes n2;
int weight;
Edge(Nodes n1,Nodes n2,int weight)
{
this.n1 = n1;
this.n2 = n2;
this.weight = weight;
}
}
class Nodes
{
Nodes parent;
int vertex;
int rank;
Nodes(int v)
{
this.vertex = v;
rank=0;
parent = this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment