解决Google Code Jam 2018第1C轮问题

时间:2018-05-08 13:25:52

标签: java algorithm

我尝试使用最长增加子序列来解决第三个问题,但未能通过小测试集。我不确定LIS是否是解决此问题的正确方法。对于连接现有堆栈的蚂蚁,堆栈的总重量必须小于或等于蚂蚁的权重乘以6.

Link to the problem

enter image description here enter image description here

请参阅下面的代码。谢谢。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Solution {

    public static void main(String[] args) throws NumberFormatException, IOException {
        // TODO Auto-generated method stub
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        int T = Integer.parseInt(reader.readLine());

        for (int i = 1; i <= T; i++) {

            int N = Integer.parseInt(reader.readLine());
            String[] temp = reader.readLine().split("[ ]");
            long[] weights = new long[N];
            for (int j = 0; j < N; j++) {
                weights[j] = Long.parseLong(temp[j]);
            }

            int result = solution(N, weights);

            System.out.println("Case #" + i + ": " + result);
        }

        reader.close();
    }

    public static int solution(int N, long[] weights) {

        long[] total = new long[N + 1];
        for (int i = 0; i < total.length; i++) {
            total[i] = -1;
        }
        total[0] = 0;

        int max = 0;

        for (int i = 0; i < N; i++) {
            long current = weights[i];
            int left = 0;
            int right = max;
            int length = -1;
            while (left <= right) {
                int mid = (right - left) / 2 + left;
                if (total[mid] != -1 && total[mid] <= 6 * current) {
                    length = mid;
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            }

            if (length != -1) {
                if (total[length + 1] == -1) {
                    total[length + 1] = total[length] + current;
                } else {
                    total[length + 1] = Math.min(total[length + 1], total[length] + current);
                }
                max = Math.max(max, length + 1);
            }
        }
        return max;
    }
}

1 个答案:

答案 0 :(得分:0)

LIS一词可能在该博文中使用不准确。显然,我们想要最长的序列,但是什么属性会增加?

鉴于蚂蚁长度增加的序列,我们向下看向桩的开始;我们可以说,通常情况下,给定一个新的权重w,任何存储在l中且权重为ls的长度为ls[l]的序列都可以更新为当前体重的较小者或ls[l - 1] + w

(基于markX's referenceanswer。)