java解决方案桥梁建设没有回答正确答案

时间:2018-05-03 16:13:18

标签: java arrays

我的代码有问题它应该返回时返回1 2.我拥有的对是:new CityPairs(6,2),new CityPairs(4,3),new CityPairs(2,6) ,新的CityPairs(1,5)。它应该返回2个桥但返回1.下面是我的代码。

class CityPairs {
    int north, south;
    public CityPairs(int north, int south){
        this.north = north;
        this.south = south;
    }

}

class CityPairsDriver {


    // function to find the maximum number
    // of bridges that can be built
    static int maxBridges(CityPairs values[], int n) {
        int lis[] = new int[n];
        for (int i = 0; i < n; i++)
            lis[i] = 1;

        Arrays.sort(values, new Comparator<CityPairs>() {
            @Override
            public int compare(CityPairs a, CityPairs b) {
                if (a.south == b.south)
                    if (a.north < b.north)
                        return -1;
                    else
                        return 1;
                else {
                    if (a.south < b.south)
                        return 1;
                    else
                        return 1;
                }
            }

        });

        // logic of longest increasing subsequence
        // applied on the northern coordinates
        for (int i = 1; i < n; i++)
            for (int j = 0; j < i; j++)
                if (values[i].north >= values[j].north && lis[i] < 1 + lis[j])
                    lis[i] = 1 + lis[j];

        int max = lis[0];
        for (int i = 1; i < n; i++)
            if (max < lis[i])
                max = lis[i];

        // required number of bridges
        // that can be built
        return max;
    }

    // Driver program to test above
    public static void main(String args[]) {
        CityPairs values[] = { new CityPairs(6, 2), new CityPairs( 4, 3 ), new CityPairs( 2, 6) , new CityPairs( 1, 5 ) };
        int n = 4;
        System.out.println("Maximum number of bridges = " + maxBridges(values, n));
    }

}

我的答案基于此:

https://www.geeksforgeeks.org/dynamic-programming-building-bridges/

1 个答案:

答案 0 :(得分:0)

你有3个返回相同的值,我认为你需要更改最后一个 所以你的问题在于比较功能