Created
November 17, 2016 18:19
-
-
Save chermehdi/906456a7d2f13acb1af35cc03fdf7264 to your computer and use it in GitHub Desktop.
Solution to Scorify Mouad's Bot
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @Author Mehdi Maick | |
* Created on 15/11/2016. | |
*/ | |
import java.util.*; | |
import java.io.*; | |
import static java.lang.Math.*; | |
public class MouadBot { | |
static ArrayList<ArrayList<Edge>> tree; | |
static int n; | |
public static void solve(Scanner fs, PrintWriter pw) { | |
int t = fs.nextInt(); | |
while (t-- > 0) { | |
int V = fs.nextInt(); | |
tree = new ArrayList<>(); | |
for (int i = 0; i < V; i++) { | |
tree.add(new ArrayList<>()); | |
} | |
long totalCost = 0L; | |
for (int i = 0; i < V * (V - 1) / 2; i++) { | |
int a = fs.nextInt(), b = fs.nextInt(); | |
long c = fs.nextLong(); | |
tree.get(a).add(new Edge(b, c)); | |
tree.get(b).add(new Edge(a, c)); | |
totalCost += c; | |
} | |
long cost = getMinimumSpanningTree(V); | |
pw.println(totalCost - cost); | |
} | |
} | |
public static long getMinimumSpanningTree(int V) { | |
long ans = 0L; | |
boolean[] visited = new boolean[V]; | |
PriorityQueue<Edge> pq = new PriorityQueue<>(); | |
pq.add(new Edge(0, 0L)); | |
while (!pq.isEmpty()) { | |
Edge e = pq.poll(); | |
if (visited[e.to]) { | |
continue; | |
} | |
ans += e.cost; | |
visited[e.to] = true; | |
for (Edge edge : tree.get(e.to)) { | |
if (!visited[edge.to]) { | |
pq.add(edge); | |
} | |
} | |
} | |
return ans; | |
} | |
static class Edge implements Comparable<Edge> { | |
long cost; | |
int to; | |
public Edge(int to, long cost) { | |
this.to = to; | |
this.cost = cost; | |
} | |
@Override | |
public int compareTo(Edge o) { | |
return Long.compare(cost, o.cost); | |
} | |
public String toString() { | |
return to + " " + cost; | |
} | |
} | |
public static void main(String[] args) throws Exception { | |
Scanner fs = new FastReader(System.in); | |
PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); | |
solve(fs, pw); | |
fs.close(); | |
pw.close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment