從一道簡單題談程序設計的思維
題目
Stick
Problem
Anthony has collected a large amount of sticks for manufacturing chopsticks. In order to simplify his job, he wants to fetch two equal-length sticks for machining at a time. After checking it over, Anthony finds that it is always possible that only one stick is left at last, because of the odd number of sticks and some other unknown reasons. For example, Anthony may have three sticks with length 1, 2, and 1 respectively. He fetches the first and the third for machinning, and leaves the second one at last. Your task is to report the length of the last stick.
Input
The input file will consist of several cases.
Each case will be presented by an integer n (1 <= n <= 100, and n is odd) at first. Following that, n positive integers will be given, one in a line. These numbers indicate the length of the sticks collected by Anthony.
The input is ended by n = 0.
Output
For each case, output an integer in a line, which is the length of the last stick.
Sample Output
2
題目分析
題意是對于給定的n(n為奇數)根木棒,其中有n - 1根是可以按長度配對的,找出按長度配對后剩余的一根木棒。
下面給出這題的幾種解法:
(1)對于每根木棒,都搜索與其匹配的另一根木棒,時間復雜度為O(n2);
(2)先將木棒按其長度排序,然后依次掃描各相鄰木棒是否匹配,時間復雜度為O(nlogn);
(3)對于任意的x,都滿足如下公式:x Xor 0 = x, x Xor x = 0。而且異或操作是滿足交換律和結合律的,因此所有配對的木棒異或后結果為0,因此將所有木棒的長度異或后得到的結果即為不成對的那根木棒的長度,時間復雜度為O(n)。
思考題
(1)有長度為1到n共n根木棒,現從中拿走某一根,再放入一根任意長度的木棒。順次輸入這n根木棒的長度,求拿走與放入木棒的長度分別是多少?
(2)有n根木棒,其中有多于一半的木棒其長度相等,順次輸入所有木棒的長度,求出這些長度相等的木棒的長度是多少?
參考資料
郭嵩山、張子臻、王磊、湯振東著 國際大學生程序設計競賽例題解(五) 電子工業出版社