今天來解YKL18(UVA10038):Jolly Jumpers
假設輸入5 1 4 2 -1 6
代表n=5的元素,序列為[1,4,2,-1,6]
計算相鄰元素的絕對差值
|4-1|=3
|2-4|=2
|-1-2|=3
|6-(-1)|=7
檢查 1 到 n-1:
上面n-1=4
所以需要差值為{1,2,3,4}
但我們得到的差值是{3,2,7},少了1和4,還多了7
所以=>"Not jolly"
下方我用了一個set不能重複的來表示
#include <iostream>
#include <vector>
#include <cmath>
#include <set>
using namespace std;
int main() {
int n;
while (cin >> n) {
vector<int> seq(n);
for (int i = 0; i < n; i++) {
//cout << i << endl;
cin >> seq[i];
}
if (n == 1) {
cout << "Jolly" << endl;
continue;
}
//不重複
set<int> diff;
for (int i = 1; i < n; i++) {
int differ = abs(seq[i] - seq[i - 1]);
if (differ >= 1 && differ <= n - 1) {
diff.insert(differ);
}
}
if (diff.size() == n - 1) {
cout << "Jolly" << endl;
} else {
cout << "Not jolly" << endl;
}
}
return 0;
}