题解:P1152 欢乐的跳

· · 题解

P1152 欢乐的跳 题解

对于本题,考虑计算每两个相邻元素的差值,然后进行排序,对每个出现的差值进行标记,最后遍历差值数组中是否包括 [1, n - 1] 之间的所有整数。

代码:

#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
int main() {
    int n, a[1005];
    cin >> n;
    if (n == 1) { //特判只有一个数的情况
        cout << "Jolly";
        return 0;
    }
    for (int i = 1; i <= n; i++) {
        cin >> a[i];
    }
    int dif[1005];
    for (int i = 1; i <= n - 1; i++) {
        dif[i] = abs(a[i + 1] - a[i]); //计算数组中连续两个元素之间差的绝对值
    }
    sort(dif + 1, dif + n); //对存储差的绝对值的数组进行排序
    bool vis[10000005] = { 0 };
    for (int i = 1; i <= n - 1; i++) {
        vis[dif[i]] = 1; //遍历dif数组,对出现过的差进行标记
    }
    for (int i = 1; i <= n - 1; i++) { //检查是否从1~n-1的每个差都出现过
        if (!vis[i]) {
            cout << "Not jolly" << endl;
            return 0;
        }
    }
    cout << "Jolly" << endl;
    return 0;
}