本文共 1935 字,大约阅读时间需要 6 分钟。
Time Limit: 1000MS | | Memory Limit: 65536K |
Total Submissions: 13365 | | Accepted: 4128 |
Description
A sequence of n > 0 integers is called a jolly jumper if the absolute values of the difference between successive elements take on all the values 1 through n-1. For instance,
1 4 2 3
is a jolly jumper, because the absolutes differences are 3, 2, and 1 respectively. The definition implies that any sequence of a single integer is a jolly jumper. You are to write a program to determine whether or not each of a number of sequences is a jolly jumper.
Input
Each line of input contains an integer n < 3000 followed by n integers representing the sequence.
Output
For each line of input, generate a line of output saying "Jolly" or "Not jolly".
Sample Input
4 1 4 2 35 1 4 2 -1 6
Sample Output
JollyNot jolly
Source
对于输入的n个数字,它们的相邻两个元素之间取绝对差值,如果这些差值为1到n-1(无论次序),就输出“Jolly”,否则输出“Not jolly”。
用一个数组subs作为标记数组,标记已经出现过差值,当出现一个差值就标记为1。当所有的差值计算完毕之后,搜索1到n-1的差值是否全部出现,如果是,
输出“Jolly”,否则输出“Not jolly”。优化:因为是n个数字,有n-1个差值,如果这些差值要取满1到n-1,则说明这些差值之间不会有重复的数字,所以在计算差值的过程中就可以进行判断,如果有重复的差值,则立刻判定“Not jolly”。 注意点: 1)计算差值的时候,要取绝对值,可以使用<cmath>里的abs(); #include #include #include #include int subs[3100];int num[3100];int main(void){ int n, i, j; int flag; while (scanf("%d", &n) != EOF){ memset(subs, 0, sizeof(subs)); flag = 1; for (i = 0; i < n; i++){ scanf("%d", &num[i]); if (i){ if (!subs[abs(num[i] - num[i - 1])]){ subs[abs(num[i] - num[i - 1])] = 1; } else{ flag = 0; } } } for (i = 1; i < n && flag; i++){ if (subs[i] != 1){ flag = 0; } } if (flag){ printf("Jolly\n"); } else{ printf("Not jolly\n"); } } return 0;}
转载地址:http://oooji.baihongyu.com/