danielvitor23

Traffic Light

Aug 19th, 2024
310
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.23 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class Main {
  4.  
  5.     static class Triple {
  6.         int to, x, y;
  7.  
  8.         Triple(int to, int x, int y) {
  9.             this.to = to;
  10.             this.x = x;
  11.             this.y = y;
  12.         }
  13.     }
  14.  
  15.     static final long INFLL = 0x3f3f3f3f3f3f3f3fL;
  16.  
  17.     static int n, m;
  18.     static long t;
  19.     static List<List<Triple>> gr;
  20.  
  21.     public static void dijkstra(long t) {
  22.         int s = 0;
  23.  
  24.         long[] dist = new long[n];
  25.         Arrays.fill(dist, INFLL);
  26.         boolean[] used = new boolean[n];
  27.  
  28.         PriorityQueue<long[]> pq = new PriorityQueue<>(Comparator.comparingLong(a -> a[0]));
  29.         dist[s] = t;
  30.         pq.offer(new long[]{t, s});
  31.  
  32.         while (!pq.isEmpty()) {
  33.             long[] current = pq.poll();
  34.             long time = current[0];
  35.             int u = (int) current[1];
  36.  
  37.             if (used[u] || time > dist[u]) continue;
  38.             used[u] = true;
  39.  
  40.             if (u == n - 1) {
  41.                 System.out.println(time);
  42.                 return;
  43.             }
  44.  
  45.             for (Triple edge : gr.get(u)) {
  46.                 int to = edge.to;
  47.                 int x = edge.x;
  48.                 int y = edge.y;
  49.                 long sum = x + y;
  50.  
  51.                 long rem = time % sum;
  52.  
  53.                 if (0 <= rem && rem < x) {
  54.                     dist[to] = time;
  55.                     pq.offer(new long[]{time, to});
  56.                 } else {
  57.                     dist[to] = time + sum - rem;
  58.                     pq.offer(new long[]{time + sum - rem, to});
  59.                 }
  60.             }
  61.         }
  62.  
  63.         System.out.println(dist[n - 1]);
  64.     }
  65.  
  66.     public static void main(String[] args) {
  67.         Scanner sc = new Scanner(System.in);
  68.         n = sc.nextInt();
  69.         m = sc.nextInt();
  70.         t = sc.nextLong();
  71.  
  72.         gr = new ArrayList<>();
  73.         for (int i = 0; i < n; i++) {
  74.             gr.add(new ArrayList<>());
  75.         }
  76.  
  77.         for (int i = 0; i < m; i++) {
  78.             int a = sc.nextInt() - 1;
  79.             int b = sc.nextInt() - 1;
  80.             int x = sc.nextInt();
  81.             int y = sc.nextInt();
  82.  
  83.             gr.get(a).add(new Triple(b, x, y));
  84.             gr.get(b).add(new Triple(a, x, y));
  85.         }
  86.  
  87.         dijkstra(t);
  88.     }
  89. }
  90.  
Advertisement
Add Comment
Please, Sign In to add comment