从一道简单题谈程序设计的思维
题目
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根木棒,其中有多于一半的木棒其长度相等,顺次输入所有木棒的长度,求出这些长度相等的木棒的长度是多少?
参考资料
郭嵩山、张子臻、王磊、汤振东著 国际大学生程序设计竞赛例题解(五) 电子工业出版社