|
| 1 | +import java.io.*; |
| 2 | +import java.util.*; |
| 3 | + |
| 4 | +class Main { |
| 5 | + |
| 6 | + static int n, m, x, y; |
| 7 | + static List<int[]>[] graph; |
| 8 | + |
| 9 | + public static void main(String[] args ) throws Exception { |
| 10 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 11 | + BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 12 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 13 | + n = Integer.parseInt(st.nextToken()); |
| 14 | + m = Integer.parseInt(st.nextToken()); |
| 15 | + x = Integer.parseInt(st.nextToken()); |
| 16 | + y = Integer.parseInt(st.nextToken()); |
| 17 | + graph = new ArrayList[n]; |
| 18 | + |
| 19 | + for (int i = 0; i < n; i++) { |
| 20 | + graph[i] = new ArrayList<>(); |
| 21 | + } |
| 22 | + |
| 23 | + for (int i = 0; i < m; i++) { |
| 24 | + st = new StringTokenizer(br.readLine()); |
| 25 | + int a = Integer.parseInt(st.nextToken()); |
| 26 | + int b = Integer.parseInt(st.nextToken()); |
| 27 | + int c = Integer.parseInt(st.nextToken()); |
| 28 | + graph[a].add(new int[]{b, c}); |
| 29 | + graph[b].add(new int[]{a, c}); |
| 30 | + } |
| 31 | + |
| 32 | + int[] dist = dijkstra(); |
| 33 | + Arrays.sort(dist); |
| 34 | + |
| 35 | + int count = 0; |
| 36 | + int sum = 0; |
| 37 | + for (int i = 1; i < n; i++) { |
| 38 | + if (dist[i] * 2 > x) { |
| 39 | + bw.write("-1"); |
| 40 | + bw.flush(); |
| 41 | + bw.close(); |
| 42 | + return; |
| 43 | + } |
| 44 | + if (sum + dist[i] * 2 <= x) { |
| 45 | + sum += dist[i] * 2; |
| 46 | + } else { |
| 47 | + count++; |
| 48 | + sum = dist[i] * 2; |
| 49 | + } |
| 50 | + } |
| 51 | + if (sum > 0) { |
| 52 | + count++; |
| 53 | + } |
| 54 | + |
| 55 | + bw.write(Integer.toString(count)); |
| 56 | + bw.flush(); |
| 57 | + bw.close(); |
| 58 | + } |
| 59 | + |
| 60 | + public static int[] dijkstra() { |
| 61 | + int[] dist = new int[n]; |
| 62 | + Arrays.fill(dist, 100_000_000); |
| 63 | + dist[y] = 0; |
| 64 | + |
| 65 | + PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(o -> o[1])); |
| 66 | + pq.offer(new int[]{y, 0}); |
| 67 | + |
| 68 | + while (!pq.isEmpty()) { |
| 69 | + int[] current = pq.poll(); |
| 70 | + |
| 71 | + for (int[] next : graph[current[0]]) { |
| 72 | + |
| 73 | + if (dist[next[0]] > current[1] + next[1]) { |
| 74 | + dist[next[0]] = current[1] + next[1]; |
| 75 | + pq.offer(new int[]{next[0], dist[next[0]]}); |
| 76 | + } |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + return dist; |
| 81 | + } |
| 82 | +} |
0 commit comments