【題目敘述】https://zerojudge.tw/ShowProblem?problemid=d097
【解題想法】n 個數字,相鄰的兩個數的差的絕對值恰好為1到n-1 (但不一定照順序出現)。
#include <iostream>
#include <cstring>
using namespace std;
int main() {
int n;
while (cin >> n){
int pre, now;
int d[n]; // initial value not guanranteed to be zero
for (int i = 0; i < n; i++) {
d[i] = 0;
}
cin >> pre;
for (int i = 1; i < n; i++){
cin >> now;
d[abs(now - pre)]++;
pre = now;
}
bool flag = true;
for (int i = 1; i < n; i++) {
if (d[i] != 1) {
flag = false;
break;
}
}
if (flag) cout << "Jolly\n";
else cout << "Not jolly\n";
}
return 0;
}
Python code (credit: Amy Chou)
while True:
try:
a = list(map(int, input().split()))
n = a[0]
a = a[1:]
d = [0 for _ in range(n)]
for i in range(1, n):
delta = abs(a[i] - a[i-1])
if delta <= n-1:
d[delta] += 1
flag = True
for i in range(1, n):
if d[i] != 1:
flag = False
break
if flag:
print("Jolly")
else:
print("Not jolly")
except:
break