阿里笔试7.24-开关灯问题

import java.util.*;
public class main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int T = Integer.parseInt(input.nextLine());
        int res = 0;
        for (int i = 0; i < T; i++) {
            String[] a = input.nextLine().split(" ");
            int N = Integer.parseInt(a[0]);
            int L = Integer.parseInt(a[1]);
            int[][] start = new int[N][L];
            int[][] target = new int[N][L];
            String[] s = input.nextLine().split(" ");
            String[] t = input.nextLine().split(" ");
            
            for (int j = 0; j < N; j++) {
                for (int k = 0; k < L; k++) {
                    start[j][k] = s[j].charAt(k) - '0';
                }
            }
            for (int j = 0; j < N; j++) {
                for (int k = 0; k < L; k++) target[j][k] = t[j].charAt(k) - '0';
            }
            System.out.println(ControlLight(N, L, start, target));
        }
    }

    public static String ControlLight(int N, int L, int[][] start, int[][] target) {
        Map mapS = new HashMap<>();
        Map mapT = new HashMap<>();
        int[] lineS = new int[L];
        int[] lineT = new int[L];
        int count = 0;
        for (int j = 0; j < L; j++) {
            for (int i = 0; i < N; i++) {
                lineS[j] += start[i][j];
            }
        }
        //System.out.println(lineS[0]);
        for (int j = 0; j < L; j++) {
            for (int i = 0; i < N; i++) {
                lineT[j] += target[i][j];
            }
        }
        //System.out.println(lineT[0]);
        for (int j = 0; j < L; j++) {
            if ((lineS[j] != lineT[j]) && (lineS[j] + lineT[j] != N)) return "impossible";
            if ((lineS[j] != lineT[j]) && (lineS[j] + lineT[j] == N)) {
                for (int i = 0; i < N; i++) {
                    start[i][j] = start[i][j] ^ 1;
                }
                count++;
            }
        }
        for (int i = 0; i < N; i++) {
            int x = 0;
            for (int j = 0; j < L; j++) {
                x = x * 2 + start[i][j];
            }
            mapS.put(i, x);
        }

        for (int i = 0; i < N; i++) {
            int x = 0;
            for (int j = 0; j < L; j++) {
                x = x * 2 + target[i][j];
            }
            if (!mapS.containsValue(x)) return "impossible";
            else {
                mapT.put(i, x);
            }
        }
        for (Integer value : mapS.values()) {
            if (!mapT.containsValue(value)) return "impossible";
        }
        return String.valueOf(count);
    }
}

测试样例通过,时间复杂度o(N*2^L)。我不会优化,有没有大佬教教我。

你可能感兴趣的:(后台)