问题描述:
- 一个长度为 n(n>0)n(n>0) 的序列中存在“有趣的跳跃”当前仅当相邻元素的差的绝对值经过排序后正好是从 11 到 (n-1)(n−1)。例如,1\ 4\ 2\ 31 4 2 3 存在“有趣的跳跃”,因为差的绝对值分别为 3,2,13,2,1。当然,任何只包含单个元素的序列一定存在“有趣的跳跃”。你需要写一个程序判定给定序列是否存在“有趣的跳跃”。
- 输入格式
- 一行,第一个数是 n(0 < n < 3000)n(0<n<3000),为序列长度,接下来有 nn 个整数,依次为序列中各元素,各元素的绝对值均不超过 1,000,000,0001,000,000,000。
- 输出格式
- 一行,若该序列存在“有趣的跳跃”,输出
"Jolly"
,否则输出"Not jolly"
。 - 输出时每行末尾的多余空格,不影响答案正确性
- 样例输入
-
4 1 4 2 3
- 样例输出
-
Jolly
代码:
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <string>
using namespace std;
int decide(int b[], int n) {
int flag = 1;
for (int i = 0; i < n - 1; i++) {
if (b[i + 1] - b[i] == 1) {
flag = 1;
}
else {
flag = 0;
}
}
if (flag == 1) return 1;
else return 0;
}
int main() {
int n; //序列长度
cin >> n;
int a[3000]; //存放数字
int b[3000] ={0}; //存放相邻差 注意 这里如果不初始化 有些结果可能会出错
for (int i = 0; i < n; i++) { //输入
cin >> a[i];
}
for (int j = 0; j < n - 1; j++) { //计算出相邻差
b[j] =abs( a[j + 1] - a[j]);
}
int temp; //借助的第三个量
for (int i = 0; i < n; i++) { //将相邻差形成的数组从小到大排序
for (int j = i; j < n - i; j++) {
if (b[j] > b[j + 1]) {
temp = b[j];
b[j] = b[j + 1];
b[j + 1] = temp;
}
}
}
if (decide(b ,n) == 1) { //注意这里调用函数的参数是 b 而不是b[]
cout << "Jolly" << endl;
}
else {
cout << "Not jolly" << endl;
}
return 0;
}