Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.Collections;
- public class mrpresident {
- static int[] arrow;
- static int find(int person) {
- if (arrow[person] == -1) {
- return person;
- }
- arrow[person] = find(arrow[person]);
- return arrow[person];
- }
- static void combineGroup(int person1, int person2) {
- person1 = find(person1);
- person2 = find(person2);
- arrow[person1] = person2;
- }
- static class Edge implements Comparable<Edge> {
- int cityA, cityB;// cities it connects
- long cost;// cost
- @Override
- public int compareTo(Edge other) {
- return Long.compare(cost, other.cost);
- }
- }
- public static void main(String[] args) throws IOException {
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- String[] line = br.readLine().split(" ");
- int n = Integer.parseInt(line[0]);
- int m = Integer.parseInt(line[1]);
- long k = Long.parseLong(line[2]);
- // initialize disjoint set
- arrow = new int[n + 6];
- Arrays.fill(arrow, -1);
- ArrayList<Edge> roads = new ArrayList<Edge>();
- // read in roads
- for (int i = 0; i < m; i++) {
- // read in line
- line = br.readLine().split(" ");
- Edge road = new Edge();
- road.cityA = Integer.parseInt(line[0]) - 1;
- road.cityB = Integer.parseInt(line[1]) - 1;
- road.cost = Long.parseLong(line[2]);
- roads.add(road);
- }
- // sort from least to most expensive
- Collections.sort(roads);
- // kruskals algorithm
- ArrayList<Edge> keptRoads = new ArrayList<Edge>();
- long totalCost = 0;
- for (Edge road : roads) {
- if (find(road.cityA) != find(road.cityB)) {
- keptRoads.add(road);
- totalCost += road.cost;
- combineGroup(road.cityA, road.cityB);
- }
- }
- // check if possible
- if (keptRoads.size() != n - 1) {
- System.out.println(-1);
- return;
- }
- Collections.sort(keptRoads);
- Collections.reverse(keptRoads);
- // start from most expensive road, and see if we need to transform it to a super
- // road
- int superRoadsUsed = 0;
- for (Edge road : keptRoads) {
- if (totalCost <= k) {
- break;
- }
- totalCost -= road.cost;
- totalCost += 1;
- superRoadsUsed++;
- }
- // not enough money
- if (totalCost > k) {
- System.out.println(-1);
- return;
- }
- System.out.println(superRoadsUsed);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement