The Problem
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.
The Input
Each line of input contains an integer n <= 3000 followed by n integers representing the sequence.
The Output
For each line of input, generate a line of output saying "Jolly" or "Not jolly".
Sample Input
4 1 4 2 3
5 1 4 2 -1 6
Sample Output
Jolly
Not jolly
解題思考
在這一題,若是輸入大小為 n,我們需要先初始化一個大小同樣為 n 的布林(boolean)陣列為非(false)。
接著,在輸入每一個數字之後,我們需要將相鄰兩數相減。若是兩數相減之絕對值落在 1 到 n - 1,就將相對應的布林陣列元素設為真(true)。
此外,因為題目要求的是:相鄰兩數其差的絕對值恰好為 1 到 n - 1,所以若是其對應的布林陣列元素早已為真,就代表其差的絕對值有重複,也就不能達到題目所求的「恰好為 1 到 n - 1」。換句話說,碰上這種情況,就代表 Not jolly 了。為了快速起見,就可以不用再做接下來的判斷。
參考解答(C++)
#include <iostream>
using namespace std;
int main(void)
{
int n;
while (cin >> n)
{
int *num = new int[n];
bool *seen = new bool[n];
bool jolly = true;
for (int i = 0; i < n; i++)
{
seen[i] = false;
}
for (int i = 0; i < n; i++)
{
cin >> num[i];
if (i && jolly)
{
int r = num[i] - num[i - 1];
if (r < 0) { r *= -1; }
if (r > n - 1 || !r || seen[r])
{
jolly = false;
}
else { seen[r] = true; }
}
}
if (jolly) { cout << "Jolly" << endl; }
else { cout << "Not jolly" << endl; }
delete [] num;
delete [] seen;
}
#ifndef ONLINE_JUDGE
system("pause");
#endif
}
2 回覆:
不好意思..我是初學者
可以解釋一下,下方的意思嗎?尤其是符號*的部分
int *num = new int[n];
bool *seen = new bool[n];
因為如果用陣列char num[100]; 去處理..
像題目的-1部分就會產生問題..
而int *num = new int[n];是代表把陣列儲存成int的意思嗎?
不好意思,我不太理解您所謂「-1 發生問題」的意思。
不過我可以先解釋一下 int *num = new int[n]; 的意思。
這裡的 int *num 代表我宣告一個指向 int 變數的指標(pointer)。
而後面的 new int[n] 代表我要動態配置一塊具有 n 個 int 型態變數的記憶體空間。
所以整行的意義,就是宣告一個名為 num 的 int 指標,指向一個動態配置的 int 陣列開頭。
如果這個部份不懂,你可能需要去查看網路或書籍。
尋找有關「動態記憶體配置(Dynamical Memory Allocation)」的部分。
張貼留言