題目要每兩個的差剛好要填滿1~n-1
也就是說所有差相加要剛好等於 ((1+n-1)*n-1 )/ 2
同時也不能有任何數字重複 所以用set去表示
#include<iostream>
#include<math.h>
#include<set>
using namespace std;
int main(){
int n;
while(cin >> n){
set s;
int total=(1+(n-1))*(n-1)/2 ;
if(n==1){
total = 0;
}
bool flag = true;
int tmp[2]={0};
cin >> tmp[0];
for(int i=1;i> tmp[i%2];
int dif = abs(tmp[0]-tmp[1]);
if(s.count(dif)==0){
s.insert(dif);
total -= dif;
}
else{
flag = false;
}
}
if(total == 0 && flag == true){
cout << "Jolly" <
另解:(直觀)
若每一次計算的差皆為新的值,則對應陣列的值加一
最後以for檢查陣列內1~n-1的值均為一
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
int main(int argc, const char * argv[]) {
int n, i;
while (scanf("%d", &n) != EOF){
int seq[3005] = {0};
bool j_or_not_j = true, check[3005] = {0};
scanf("%d", &seq[0]);
for (i = 1; i < n; i++) {
scanf("%d", &seq[i]);
check[abs(seq[i]-seq[i-1])]++;
}
for (i = 1; i < n; i++) {
if (check[i] != 1) {
j_or_not_j = false;
break;
}
}
if (j_or_not_j)
printf("Jolly\n");
else
printf("Not jolly\n");
}
return 0;
}
沒有留言:
張貼留言