Untitled
import java.util.*; import java.lang.Math; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; public class Solution { public static int minimumCost(int N, List<Integer> A, List<List<Integer>> Cost) { // Convert A to 0-based indexing for easier comparison List<Integer> A0b = new ArrayList<>(N); for (int i = 0; i < N; i++) { A0b.add(A.get(i) - 1); } int[][] dp = new int[N + 1][1 << N]; for (int[] row : dp) { Arrays.fill(row, Integer.MAX_VALUE / 2); // Use /2 to avoid overflow when adding costs } dp[0][0] = 0; for (int i = 0; i < N; i++) { for (int mask = 0; mask < (1 << N); mask++) { if (dp[i][mask] == Integer.MAX_VALUE / 2) continue; for (int j = 0; j < N; j++) { if ((mask & (1 << j)) == 0) { int newMask = mask | (1 << j); dp[i + 1][newMask] = Math.min(dp[i + 1][newMask], dp[i][mask] + Cost.get(i).get(j)); } } } } int answer = Integer.MAX_VALUE; for (int mask = 0; mask < (1 << N); mask++) { if (isLexicographicallyValid(mask, A0b)) { answer = Math.min(answer, dp[N][mask]); } } return answer; } private static boolean isLexicographicallyValid(int mask, List<Integer> A) { int index = 0; List<Integer> B = new ArrayList<>(); for (int i = 0; i < A.size(); i++) { if ((mask & (1 << i)) != 0) { B.add(i); } } for (; index < A.size() && B.size() > index; index++) { if (B.get(index) < A.get(index)) return true; if (B.get(index) > A.get(index)) return false; } return true; } public static void main(String[] args) { Scanner scan = new Scanner(System.in); int N = Integer.parseInt(scan.nextLine().trim()); List<Integer> A = new ArrayList<>(N); for (int j = 0; j < N; j++) { A.add(Integer.parseInt(scan.nextLine().trim())); } List<List<Integer>> Cost = new ArrayList<>(N); for (int i = 0; i < N; i++) { Cost.add( Arrays.asList(scan.nextLine().trim().split(" ")) .stream().map(s -> Integer.parseInt(s)) .collect(toList()) ); } int result = minimumCost(N, A, Cost); System.out.println(result); } }
Leave a Comment