The Problem
Now that you're back to school for another term, you need to remember how to work the combination lock on your locker. A common design is that of the Master Brand, shown at right. The lock has a dial with 40 calibration marks numbered 0 to 39. A combination consists of 3 of these numbers; for example: 15-25-8. To open the lock, the following steps are taken:
- turn the dial clockwise 2 full turns
- stop at the first number of the combination
- turn the dial counter-clockwise 1 full turn
- continue turning counter-clockwise until the 2nd number is reached
- turn the dial clockwise again until the 3rd number is reached
- pull the shank and the lock will open.
Input
Input consists of several test cases. For each case there is a line of input containing 4 numbers between 0 and 39. The first number is the position of the dial. The next three numbers are the combination. Consecutive numbers in the combination will be distinct. A line containing 0 0 0 0 follows the last case.
Output
For each case, print a line with a single integer: the number of degrees that the dial must be turned to open the lock.
Sample Input
0 30 0 30
5 35 5 35
0 20 0 20
7 27 7 27
0 10 0 10
9 19 9 19
0 0 0 0
Sample Output
1350
1350
1620
1620
1890
1890
解題思考
這題看起來好像有點複雜,不過找出公式之後問題便可以迎刃而解。
讓我們先分別求出題目五個步驟的角度值。
首先,假設每一筆輸入資料的四個號碼分別為 d0、d1、d2、d3。且由於轉盤共有 40 個刻度,所以一個刻度的角度值恰好為 9。
- 第一步,我們順時針旋轉兩圈。所以旋轉的角度值為:720 度。
- 第二步,我們由起始數字 d0 順時針旋轉到第一個號碼 d1。所以若是 d0 > d1,旋轉的角度值為:(d0 - d1) × 9 度;若是 d0 < d1,旋轉的角度值為:(d0 - d1 + 40) × 9 度。
- 第三步,我們逆時針旋轉一圈。所以旋轉的角度值為:360 度。
- 第四步,我們由第一個數字 d1 逆時針旋轉到第二個號碼 d2。所以若是 d2 > d1,旋轉的角度值為:(d2 - d1) × 9 度;若是 d2 < d1,旋轉的角度值為:(d2 - d1 + 40) × 9 度。
- 第五步,我們從第二個號碼 d2 順時針旋轉到第三個號碼 d3。所以若是 d2 > d3,旋轉的角度值為:(d2 - d3) × 9 度;若是 d2 < d3,旋轉的角度值為:(d2 - d3 + 40) × 9 度。
參考解答(C++)
#include <iostream> using namespace std; int main(void) { while (1) { int d[4]; cin >> d[0] >> d[1] >> d[2] >> d[3]; if (d[0] == 0 && d[1] == 0 && d[2] == 0 && d[3] == 0) { break; } // 計算角度 int degree = 120; degree += (d[0] - d[1] + 40) % 40; degree += (d[2] - d[1] + 40) % 40; degree += (d[2] - d[3] + 40) % 40; cout << degree * 9 << endl; } #ifndef ONLINE_JUDGE system("pause"); #endif return 0; }
5 回覆:
轉盤式密碼鎖確實是順逆順321
題目沒寫錯阿
不, 你拿 Sample Input 的數值手算看看
題目的順逆時針與 Sample Output 的結果不合
0 30 0 30
0順時針到30有10刻度
30逆時針到0共10刻度
0順時針到30有10刻度
共30 * 9 + 1080 = 1350度
沒搞錯阿@@
是我搞錯了, 不好意思 囧>
請問為甚麼要加40?
張貼留言