Skip to content

1083 是否存在相等的差

给定 N 张卡片,正面分别写上 1、2、……、N,然后全部翻面,洗牌,在背面分别写上 1、2、……、N。将每张牌的正反两面数字相减(大减小),得到 N 个非负差值,其中是否存在相等的差?

输入格式:

输入第一行给出一个正整数 N(2 ≤ N ≤ 10 000),随后一行给出 1 到 N 的一个洗牌后的排列,第 i 个数表示正面写了 i 的那张卡片背面的数字。

输出格式:

按照“差值 重复次数”的格式从大到小输出重复的差值及其重复的次数,每行输出一个结果。

输入样例:

tex
8
3 5 8 6 2 1 4 7
8
3 5 8 6 2 1 4 7

输出样例:

tex
5 2
3 3
2 2
5 2
3 3
2 2

Solution:

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

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(in.readLine());
        String[] a = in.readLine().split(" ");
        int[] numbers = new int[a.length];
        for (int i = 0; i < n; i++) {
            numbers[i] = Integer.parseInt(a[i]);
        }
        int[] res = new int[10001];
        for (int i = 0; i < n; i++) {
            res[Math.abs(numbers[i] - (i + 1))]++;
        }
        for (int i = res.length - 1; i >= 0; i--) {
            if (res[i] > 1) {
                System.out.println(i + " " + res[i]);
            }
        }
    }
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(in.readLine());
        String[] a = in.readLine().split(" ");
        int[] numbers = new int[a.length];
        for (int i = 0; i < n; i++) {
            numbers[i] = Integer.parseInt(a[i]);
        }
        int[] res = new int[10001];
        for (int i = 0; i < n; i++) {
            res[Math.abs(numbers[i] - (i + 1))]++;
        }
        for (int i = res.length - 1; i >= 0; i--) {
            if (res[i] > 1) {
                System.out.println(i + " " + res[i]);
            }
        }
    }
}

Released under the MIT License.