TLE求救
查看原帖
TLE求救
192019
huzpsb楼主2023/9/16 22:19
// https://www.luogu.com.cn/problem/P9235

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int device, connection, query;
        device = sc.nextInt();
        connection = sc.nextInt();
        query = sc.nextInt();

        Connection[] cs = new Connection[connection];
        for (int i = 0; i < connection; i++) {
            Connection c = new Connection();
            c.a = sc.nextInt() - 1;
            c.b = sc.nextInt() - 1;
            c.val = sc.nextInt();
            cs[i] = c;
        }

        for (int i = 0; i < query; i++) {
            PriorityQueue<Task> toScan = new PriorityQueue<>(new TaskCmp());
            int from = sc.nextInt() - 1;
            int to = sc.nextInt() - 1;
            int[] state = new int[device];
            for (int j = 0; j < device; j++) {
                state[j] = Integer.MIN_VALUE;
            }
            Task init = new Task();
            init.target = from;
            init.connectivity = Integer.MAX_VALUE;
            toScan.offer(init);
            while (true) {
                Task t = toScan.poll();
                if (t == null) {
                    break;
                }
                if (state[t.target] >= t.connectivity) {
                    continue;
                }
                state[t.target] = t.connectivity;
                for (Connection c : cs) {
                    if (c.a == t.target) {
                        Task update = new Task();
                        update.target = c.b;
                        update.connectivity = Math.min(c.val, t.connectivity);
                        if (update.connectivity > state[c.b]) {
                            toScan.offer(update);
                        }
                    } else if (c.b == t.target) {
                        Task update = new Task();
                        update.target = c.a;
                        update.connectivity = Math.min(c.val, t.connectivity);
                        if (update.connectivity > state[c.a]) {
                            toScan.offer(update);
                        }
                    }
                }
            }
            int len = state[to];
            if (len == Integer.MIN_VALUE) {
                len = -1;
            }
            System.out.println(len);
        }
    }
}

class Task {
    int target;
    int connectivity;
}

class Connection {
    int a;
    int b;
    int val;
}

class TaskCmp implements Comparator<Task> {
    @Override
    public int compare(Task o1, Task o2) {
        return -o1.connectivity + o2.connectivity;
    }
}

2023/9/16 22:19
加载中...