随机排列并计算排列中a [i] <a [i + 1]的位置

时间:2018-11-12 07:24:28

标签: java permutation

第一行包含马拉松次数t < 100。每个马拉松比赛由三行指定。第一行包含跑步人数1 < n <= 40000。第二行是起始编号1,...,n的排列,代表运动员通过起始行的顺序。最后,第三行是代表完成顺序的排列。对于每项马拉松比赛输出,其中一行包含了比赛中发生的最少超车次数。

例如

Input Output

我真的不知道如何创建随机排列1 < n以及如何确定发生了多少次超车。对于后者,我将检查比下一个大多少个数字,即如果4 > 3则增加一个整数overtaking++;

import java.util.Scanner;

public class MarathonMovement {

   public static void main(String[] args) {

       Scanner NoM = new Scanner(System.in); // Number of marathons
       int t = NoM.nextInt();

       Scanner NoR = new Scanner(System.in); // First line: Number of runners
       int n = NoR.nextInt();

       // Second line: Permutation of starting numbers representing the order in which the runners passed the starting line

       // Third line: Permutation which represents finishing order

        int overtakings = 0;

        for (int i = 0; i < n; i++){
           if {
               // logic
               overtakings++;
           }
        }

       for(int x = 0; x < t; x++){
          System.out.println("at least" + overtakings + " overtaking(s)");
       }
   }
}

2 个答案:

答案 0 :(得分:1)

如果我正确理解此任务,那么这是我的解决方案:

public static void main(String... args) {
    try (Scanner scan = new Scanner(System.in)) {
        int t = scan.nextInt();

        for (int i = 0; i < t; i++) {
            int n = scan.nextInt();
            int[] arr = new int[n];
            Set<String> uniqueOvertaking = new HashSet<>();

            for (int j = 0; j < n; j++)
                arr[j] = scan.nextInt();
            for (int j = 0; j < n; j++) {
                int val = scan.nextInt();

                if (arr[j] != val)
                    uniqueOvertaking.add(Math.min(arr[j], val) + "->" + Math.max(arr[j], val));
            }

            int res = uniqueOvertaking.size() == n ? uniqueOvertaking.size() - 1 : uniqueOvertaking.size();
            System.out.println("at least " + res + " overtaking(s)");
        }
    }
}

输出:

at least 1 overtaking(s)
at least 5 overtaking(s)
at least 3 overtaking(s)

答案 1 :(得分:1)

对于问题的第一部分(生成随机排列),可以使用Collections.shuffle方法:

    List<Integer> start = new ArrayList<>();
    for (int i = 0; i < n; ++i) {
        start.add(i + 1);
    }
    List<Integer> finish = new ArrayList<>(start);
    Collections.shuffle(finish);

要计算超车量:

    int overtakings = 0;
    for (int i = 1; i < n; ++i) {
        if (finish.get(i) < finish.get(i-1)) {
            ++overtakings;
        }
    }