CCF(Java)之公共钥匙盒子(_20170902)


import java.util.Scanner;

/**
 * @author kyp
 * @time 2019/9/25
 * @description
 */
public class Test {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int N = scanner.nextInt();
        int K = scanner.nextInt();
        int[][] a = new int[K][2];
        int[][] b = new int[K][2];
        int[] ret = new int[N];

        for (int i = 0; i < K; i++) {
            a[i][0] = scanner.nextInt();
            b[i][0] = a[i][0];
            a[i][1] = scanner.nextInt();
            b[i][1] = scanner.nextInt() + a[i][1];
        }
        scanner.close();

        sortMin(K, a);
        sortMin(K, b);
        for (int i = 0; i < N; i++) {
            ret[i] = i + 1;
        }

        int j = 0;
        for (int i = 0; i < K; i++) {
            if (a[i][1] < b[j][1]) {
                retInstead(ret, a[i][0], -1);
            } else if (a[i][1] == b[j][1]) {//小的先还,前面排序已经小的先排了
                retInstead(ret, -1, b[j][0]);//先还再借
//                retInstead(ret, a[i][0], -1);//多了这个扣掉50分
                j++;
                i--;
            } else {
                retInstead(ret, -1, b[j][0]);
                j++;
                i--;
            }
        }

        for (; j < K; j++) {
            retInstead(ret, -1, b[j][0]);
        }

        for (int i = 0; i < N; i++) {
            System.out.print(ret[i] + " ");
        }
    }

    public static void sortMin(int k, int[][] b) {
        for (int i = 0; i < k; i++) {
            for (int j = i + 1; j < k; j++) {
                if (b[i][1] > b[j][1]) {
                    int[] temp = b[i];
                    b[i] = b[j];
                    b[j] = temp;
                } else if (b[i][1] == b[j][1]) {
                    if (b[i][0] > b[j][0]) {
                        int[] temp = b[i];
                        b[i] = b[j];
                        b[j] = temp;
                    }
                }
            }
        }
    }

    public static int[] retInstead(int[] array, int judge, int insteadValue) {
        for (int m = 0; m < array.length; m++) {
            if (array[m] == judge) {
                array[m] = insteadValue;
                break;
            }
        }

        return array;
    }

}

以前做了很多遍测试用例都ok,但是得分才10分,痛定思痛去网上看别人的答案,看的我不大理解;就一步一步去调试了,发现重点是在于先还后借这个,就是我注释掉50分的那个;思路很简单就是:排序--先还后借--剩下的全部还掉;其中,借的时候置为-1,这样还的时候就是找-1的位置把值替换掉就好了,这样就是2个for循环,给个测试用例

1 2 3

3 3 2

2 5 7

答案是1 2 3 4 5,我之前加上注释的那句得到的错误答案是1 3 2 4 5


CCF(Java)之公共钥匙盒子(_20170902)_第1张图片

你可能感兴趣的:(CCF)