|
| 1 | +```java |
| 2 | +import java.util.*; |
| 3 | +import java.io.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 7 | + static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 8 | + static StringTokenizer st; |
| 9 | + static int N,M; |
| 10 | + static int[] arr; |
| 11 | + static int[][] manipulation; |
| 12 | + static int[] correct; |
| 13 | + static int ans = -1; |
| 14 | + |
| 15 | + public static void main(String[] args) throws Exception { |
| 16 | + N = Integer.parseInt(br.readLine()); |
| 17 | + arr = new int[N+1]; |
| 18 | + |
| 19 | + st = new StringTokenizer(br.readLine()); |
| 20 | + for (int i = 1; i <= N; i++) { |
| 21 | + arr[i] = Integer.parseInt(st.nextToken()); |
| 22 | + } |
| 23 | + correct = Arrays.copyOf(arr, N+1); |
| 24 | + Arrays.sort(correct); |
| 25 | + |
| 26 | + M = Integer.parseInt(br.readLine()); |
| 27 | + manipulation = new int[M][3]; |
| 28 | + |
| 29 | + for (int i = 0; i < M; i++) { |
| 30 | + st = new StringTokenizer(br.readLine()); |
| 31 | + int a = Integer.parseInt(st.nextToken()); |
| 32 | + int b = Integer.parseInt(st.nextToken()); |
| 33 | + int c = Integer.parseInt(st.nextToken()); |
| 34 | + manipulation[i] = new int[]{a,b,c}; |
| 35 | + } |
| 36 | + |
| 37 | + dijkstra(); |
| 38 | + |
| 39 | + bw.write(ans+""); |
| 40 | + bw.close(); |
| 41 | + } |
| 42 | + static void dijkstra(){ |
| 43 | + PriorityQueue<int[]> pq = new PriorityQueue<>((a,b) -> a[0]-b[0]); |
| 44 | + Map<String, Integer> dist = new HashMap<>(); |
| 45 | + pq.offer(arr); |
| 46 | + dist.put(Arrays.toString(Arrays.copyOfRange(arr,1,N+1)),0); |
| 47 | + |
| 48 | + while (!pq.isEmpty()){ |
| 49 | + int[] cur = pq.poll(); |
| 50 | + String curString = Arrays.toString(Arrays.copyOfRange(cur,1,N+1)); |
| 51 | + |
| 52 | + if(dist.get(curString) < cur[0]) continue; |
| 53 | + |
| 54 | + for(int i = 0; i<M; i++){ |
| 55 | + int[] next = Arrays.copyOf(cur,N+1); |
| 56 | + next[manipulation[i][1]] = cur[manipulation[i][0]]; |
| 57 | + next[manipulation[i][0]] = cur[manipulation[i][1]]; |
| 58 | + int newDist = dist.get(curString) + manipulation[i][2]; |
| 59 | + next[0] = newDist; |
| 60 | + String nextString = Arrays.toString(Arrays.copyOfRange(next,1,N+1)); |
| 61 | + if(dist.get(nextString) == null || newDist < dist.get(nextString)){ |
| 62 | + dist.put(nextString, newDist); |
| 63 | + pq.offer(next); |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + ans = dist.getOrDefault(Arrays.toString(Arrays.copyOfRange(correct,1,N+1)), -1); |
| 68 | + } |
| 69 | +} |
| 70 | +``` |
0 commit comments