【问题标题】:Make array sorted using given operations使用给定的操作对数组进行排序
【发布时间】:2015-04-03 15:58:15
【问题描述】:

给定一个标记为 1 到 M 的 M 个数字列表。我们还给出了 Q 类型的操作:X Y

每个操作意味着我们可以简单地将值为 X 的数字更改为值为 Y 的数字,反之亦然。操作也是可传递的。这意味着如果 X->Y 和 Y->Z 则 X 也可以更改为 Z。

现在给定一个由 N 个数字组成的序列,我们需要通过修改最小数字数使其按递增顺序(可能不是严格递增)排序。如果不可能,则返回 -1 告诉它不可能。

示例:假设我们有 3 个数字(=M)和 3 个操作(=Q)如下:

1 2
2 3
1 3

并且让 N=3 将数组修改为 [3,2,1] 那么答案是 2(因为我们修改了数组中的 2 个数字),因为可以将第一个数字转换为 1,将最后一个数字转换为 2 . 结果数组是 [1,2,2] ,它正在增加。

但是让 M=3 并且我们只有一个操作:2 3 。也让 N=2 和数组为 [2,1] 则无法对其进行排序,因为它只能转换为 [2,1] 或 [3,1]。

那么如何解决这个问题呢?请帮忙

假设 M 最大可以是 200 ,所以我们可以找到从特定数字可以达到的数字。但我无法解决它,因为 N 可以达到 200000。那么如何维护数组是否排序。我认为DP可以提供帮助,但还没有任何线索。

【问题讨论】:

  • Q 中的运算是可交换的吗?否则我不听你的解释。另外你从哪里得到N?您在示例中同时使用了 M 和 N,但您从未在问题描述中定义 N。
  • @KonsolLabapen 是的,它们是可交换的。我在问题陈述中定义了 N。 N 是要修改的数组中元素的数量,M 是可用的数字
  • @Asad 操作只是用一个特定的其他值替换一个特定的值,是的操作是可传递的。另外我们不需要看到操作的计数。我们需要通过改变数组中的最小数字来使数组排序
  • 一个操作只能使用一次吗?
  • 我投票决定将此问题作为离题结束,因为它试图为正在进行的竞赛获取答案。

标签: algorithm dynamic-programming


【解决方案1】:

这是用于创建算法的说明。

首先将给定 X 的所有 Y 组装到一个 Map 中。然后将给定 Y 的所有 X 组合起来。这样您最终将得到数据结构 Map<Key,Value> 为 Map<Integer,List<Integer>>。例如,如果 Q 是

1  2
2  3
1  3
4  3

那么对于 X=1,您将有一个 Map 条目为 <1,{2,3}>。所以完整的映射将是

<1,{2,3}>
<2,{1,3}>
<4,{3}>
<3,{1,2,4}>

请注意,由于 Q 是一组可交换操作,我们不需要为 2 提供两个键,尽管两个同时显示为 X 和 Y。所以我希望你能够遵循到目前为止,因为整个算法都休息在这个映射上。然后是算法。

package algorithm;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class SortArray {

    /**
     * Given an array and a set of commutative and transitive exchanges, sort the array in
     * increasing order. return the number of operations it took to sort the array.
     * 
     * @param input
     * @param operations
     * @return
     */
    static int sortArray(int[] input, int[][] operations) {
        int ops = 0;
        Map<Integer, Set<Integer>> map = flattenOperations(operations);
        int min = smallestElement(operations);
        for (int i = 0; i < input.length; i++) {
            ops += minimize(i, input, min, map);
        }

        if (isSortedAscending(input)) {
            return ops;
        } else {
            return -1;
        }

    }

    /**
     * the given array is a set of {X,Y} pairs as in {{X0,Y0},{X1,Y1},...}.
     * This method assembles all the Xs for a given Y and then all the Ys for a given X.
     * This is okay because the operations are commutative.
     * 
     * @param operations
     * @return
     */
    static private Map<Integer, Set<Integer>> flattenOperations(int[][] operations) {
        Map<Integer, Set<Integer>> map = new HashMap<Integer, Set<Integer>>();
        // add Ys for X keys
        for (int[] operation : operations) {
            Set<Integer> s = map.get(operation[0]);
            if (s == null) {
                s = new TreeSet<Integer>();
                s.add(operation[1]);
                map.put(operation[0], s);
            } else {
                s.add(operation[1]);
            }
        }

        for (int[] operation : operations) {
            Set<Integer> s = map.get(operation[1]);
            if (s == null) {
                s = new HashSet<Integer>();
                s.add(operation[0]);
                map.put(operation[1], s);
            } else {
                s.add(operation[0]);
            }
        }
        return map;
    }

    static private int smallestElement(int[][] operations) {
        int min = Math.min(operations[0][0], operations[0][1]);
        for (int i = 1; i < operations.length; i++) {
            int tmpMin = Math.min(operations[i][0], operations[i][1]);
            min = Math.min(min, tmpMin);
        }
        return min;
    }

    /**
     * Replace the element at the given index i with the minimum value possible. The minimum value
     * possible is greater than or equal to min but less than the original value at input[i]. If
     * the operation was successful return the number of exchanges, else return 0. This is a
     * subroutine. It makes sense in the greater context. This may not end in a sorted array. But
     * the caller is responsible for checking for sorting at a later point.
     * 
     * 
     * @param i
     * @param input
     * @param min
     * @param map
     * @return
     */
    static private int minimize(int i, int[] input, int min, Map<Integer, Set<Integer>> map) {
        int key = input[i];
        boolean done = false;
        int ops = 0;
        while (!done) {
            int tmp = findSmallestValueLessThanKeyButGreaterThanOrEqualToMin(key, min, map);
            if (-1 != tmp) {
                key = tmp;
                ops++;
            } else {
                done = true;
            }
        }
        input[i] = key;
        return ops;
    }

    /**
     * The lists are assumed to be pre-sorted in ascending order so that the smallest value is at
     * index 0.
     * 
     * @param key
     * @param min
     * @param map
     * @return
     */
    static private int findSmallestValueLessThanKeyButGreaterThanOrEqualToMin(int key, int min, Map<Integer, Set<Integer>> map) {
        Set<Integer> set = map.get(key);
        if (null != set) {
            for (int el : set) {
                if (el < key && el >= min) {
                    return el;
                }
            }
        }
        return -1;
    }

    static private boolean isSortedAscending(int[] input) {
        for (int i = 1; i < input.length; i++) {
            if (input[i - 1] > input[i]) {
                return false;
            }
        }
        return true;
    }

    // ====================================================================================
    public static void main(String[] args) {
        // int[][] Q = { { 1, 2 }, { 2, 3 }, { 1, 3 } };
        // int[] input = { 3, 2, 1 };
        int[][] Q = { { 2, 3 } };
        int[] input = { 2, 1 };

        int ops = sortArray(input, Q);
        System.out.println("Number of operations is " + ops);
        System.out.println("The new array is " + Arrays.toString(input));
    }
}

【讨论】:

  • 很少有查询。查询一:sort函数中的M数组是什么?
  • 也没有得到你在最小化功能中尝试做的事情。以上我几乎得到了所有
  • 我想给你一个数组和一组操作 Q。我把输入数组称为 M。如果你愿意,你可以叫它input[]
  • 我已经编辑给你一点。但我已经为你完成了 90% 的工作。在这一点上,任何更多的信息都意味着完成剩下的 10%。
  • 由于现在我有两个困惑的读者而不是一个,我将通过编辑提出整个答案,然后我们可以在你们在自己的机器上运行代码后进行更多讨论。
猜你喜欢
  • 2020-12-27
  • 1970-01-01
  • 1970-01-01
  • 2018-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多