如有更好的錯誤請指證,如有更好的想法但願能夠不吝嗇的分享,感謝
另外感謝Lucky貓的 UVA(ACM)園地的翻譯html
題目的意思其實是要表達1~n個數裡,全部兩個數之間的差值要有1~n-1,那就是jolly.
因此能夠用一個長度為n的array紀錄1~n-1是否都存在(為了方便array[0]則捨棄不用)spa
仔細思考可得如下幾點:code
若兩數差值為k, k > length(array)-1
則 not jolly (根據上述只記錄1~n-1的值因此不能大於n-1)htm
記錄完全部兩數差值之後,檢查1~n-1的值皆存在則為jollyblog
#include <iostream> #include <cmath> using namespace std; bool check(int *nums,bool *record,int length){ for(int i = 1 ; i < length ; i++){ int temp = abs(nums[i] - nums[i-1]); if(temp > length - 1) return false; record[temp] = true; } for(int i = 1 ; i < length ; i++){ if(!record[i]) return false; } return true; } int main(){ int length; while(cin >> length){ int nums[3001] = {0}; bool record[3001]= {false}; for(int i = 0 ; i < length ; i++){ cin >> nums[i]; } if(check(nums,record,length)) cout << "Jolly" << endl; else cout << "Not jolly" << endl; } }
另外一種解法一樣是使用表格記錄,只是用了不一樣的判斷方式:ci
在記錄兩數差值k的時候,順便去看錶格,若是k本來已經存在,則為not jolly (因為有n個數)get
若兩數的差值k, k = 0
或 k > length - 1
則 not jolly.io
若不為not jolly,則為 jollypdf
bool check(int *nums,bool *record,int length){ for(int i = 1 ; i < length ; i++){ int temp = abs(nums[i] - nums[i-1]); if(temp > length - 1 || temp == 0 || record[temp]) return false; record[temp] = true; } return true; }