1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| class Solution { public long getMaxFunctionValue(List<Integer> receiver, long k) { int n = receiver.size(); int[] in = new int[n]; List<Integer>[] reverse = new List[n]; Arrays.setAll(reverse, r -> new ArrayList<>()); for (int i = 0; i < n; i++) { in[receiver.get(i)]++; reverse[receiver.get(i)].add(i); } Queue<Integer> q = new LinkedList<>(); for (int i = 0; i < n; i++) { if (in[i] == 0) q.add(i); } while (!q.isEmpty()) { int x = q.poll(); if (--in[receiver.get(x)] == 0) { q.offer(receiver.get(x)); } } int[] cirNum = new int[n]; int[] cirPos = new int[n]; boolean[] vis = new boolean[n]; List<List<Long>> circles = new ArrayList<>(); for (int i = 0; i < n; i++) { if (!vis[i] && in[i] != 0) { List<Long> cir = new ArrayList<>(); cir.add(0L); for (int cur = i; !vis[cur]; cur = receiver.get(cur)) { vis[cur] = true; cirNum[cur] = circles.size(); cirPos[cur] = cir.size(); cir.add((long) cur); } for (int t = cir.size() - 1, j = 1; t > 0; t--, j++) { cir.add(cir.get(j)); } for (int j = 1; j < cir.size(); j++) { cir.set(j, cir.get(j) + cir.get(j - 1)); } circles.add(cir); } } long ans = 0L; List<Long> outSum = new ArrayList<>(); outSum.add(0L); for (int i = 0; i < n; i++) { if (in[i] != 0) ans = Math.max(ans, dfs(i, circles.get(cirNum[i]), cirPos[i], reverse, in, outSum, k + 1)); } return ans; }
private long dfs(int x, List<Long> cir, int pos, List<Integer>[] reverse, int[] in, List<Long> outSum, long k) { long res = 0L; int outLen = outSum.size() - 1; if (outLen < k) { int n = cir.size() / 2; res = (k - outLen) / n * cir.get(n) + cir.get(pos + (int) ((k - outLen) % n) - 1) - cir.get(pos - 1); } res += outSum.get(outLen) - outSum.get((int) Math.max(0L, outLen - k)); for (int y : reverse[x]) { if (in[y] != 0) continue; outSum.add(outSum.get(outLen) + y); res = Math.max(res, dfs(y, cir, pos, reverse, in, outSum, k)); outSum.remove(outLen + 1); } return res; } }
|