Ms. W has been abducted by A Sloth Monster. Now, as her boyfriend, its the duty of Mr. S to save her.
To defeat The Slothy Monster, and save Ms. W from becoming a sloth creature, he has to reach at the certain level of fighting skill.
Currently, he is at the X'th level and he has to reach the Y'th level of fighting skill.
There are different transition method available.
If you choose i'th transition method it will take you from Ai level to Bi level with the cost of Zi amount of stamina(Reverse is also true).
And if he is at skill level i, he can eat a certain Devil Fruit specific to that level which will make him sleep for Hi hours and after that make his stamina equal to Ci.
Example:
Input:
3 3 1 3
1 2 2
1 3 3
3 2 1
2 7
2 7
3 6
Output: 14
Approach
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.Comparator;import java.util.PriorityQueue;public class SavingMsW {public static void main(String[] args) {int n = 3;int m = 3;int s = 1;int e = 3;ArrayList<long[]> g[] = new ArrayList[n + 1];ArrayList<long[]> sleep[] = new ArrayList[n + 1];for (int i = 0; i <= n; i++) {g[i] = new ArrayList<>();sleep[i] = new ArrayList<>();}int arr[] = { 1, 1, 3 };int brr[] = { 2, 3, 2 };long zrr[] = { 2, 3, 1 };for (int i = 0; i < m; i++) {int a = arr[i];int b = brr[i];long z = zrr[i];g[a].add(new long[] { b, z });g[b].add(new long[] { a, z });}int c[] = new int[n + 1];int h[] = new int[n + 1];int crr[] = { 2, 2, 3 };int hrr[] = { 7, 7, 6 };for (int i = 1; i <= n; i++) {c[i] = crr[i - 1];h[i] = hrr[i - 1];}for (int i = 1; i <= n; i++) {long sl[] = shortest(g, i, n);for (int j = 1; j <= n; j++) {if (sl[j] <= c[i]) {sleep[i].add(new long[] { j, h[i] });}}}long ans[] = shortest(sleep, s, n);System.out.println(ans[e] != Long.MAX_VALUE / 2 ? ans[e] : -1);}static long[] shortest(ArrayList<long[]>[] g, int start, int n) {long res[] = new long[n + 1];Arrays.fill(res, Long.MAX_VALUE / 2);res[start] = 0;PriorityQueue<long[]> pq = new PriorityQueue<>(new Comparator<long[]>() {@Overridepublic int compare(long[] o1, long[] o2) {return Long.compare(o1[1], o2[1]);}});pq.add(new long[] { start, 0 });while (!pq.isEmpty()) {int from = (int) pq.peek()[0];long d = pq.peek()[1];pq.poll();for (long tar[] : g[from]) {int t = (int) tar[0];if ((d + tar[1]) < res[t]) {res[t] = d + tar[1];pq.add(new long[] { t, res[t] });}}}return res;}}class Pair {int a;int b;public Pair(int a, int b) {this.a = a;this.b = b;}}
No comments:
Post a Comment