1. 程式人生 > >1、誰是幸運兒--賽碼網周考(0609)

1、誰是幸運兒--賽碼網周考(0609)

重新 name 年會 log 思路 pre 如果 blog iter

時間限制:C/C++語言 2000MS;其他語言 4000MS 內存限制:C/C++語言 65536KB;其他語言 589824KB 題目描述: 小A是某公司的員工,在一次公司年會上,主持人宣布進行一項遊戲來活躍年會氣氛,遊戲規則如下:n個人隨機站成一排,按照他們所站的順序依次給他們編號從1到n,接下來就從編號為1的人開始,按從左到右的順序每隔一人選出一個人,選出的這些被淘汰,剩下的需要重新站成一排,其中首尾是接龍的,即如果倒數第二個被淘汰,則隔一人即第一個人被淘汰,如此循環一直到最後剩下兩個人為止,那麽這剩下的最後兩個人就是本場晚會的幸運兒,得到神秘大獎,小A想成為這個幸運兒,請你幫小A算出來開始時他應該站在什麽位置才最終可以成為幸運兒。(3<=n<=50) 輸入 開始的進行遊戲的總人數n 輸出 第一行是選出順序,第二行是兩名幸運兒的初始位置(按升序排列),要求位置編號之間用一個空格空開。 樣例輸入 5 樣例輸出 2 4 1 5 3 解題思路一:定義鏈表來存儲,然後讓鏈表的尾指針的下一個指向頭,構成環形鏈表
再從頭開始遍歷,每次輸出p->next,為刪除的內容;p->next = p->next->next,剩兩個結點時,p->next->next = p本身,因此可知循環截止條件。輸出剩余的兩個結點即可
 1 #include <iostream>
 2 #include <malloc.h>
 3 using namespace std;
 4 typedef struct list{
 5     struct list *next;
 6     int elem;
 7 } list ;
 8  
 9 int main()
10 { 11 int n; 12 int i; 13 list *head; 14 list *p; 15 while(cin>>n) 16 { 17 p = (list*)malloc(sizeof(list)); 18 p ->elem = 1; 19 head = p; 20 for(i = 2;i<=n;i++) 21 { 22 p->next = (list*)malloc(sizeof(list)); 23
p->next ->elem = i; 24 p = p->next; 25 } 26 p->next = head; 27 p = head; 28 29 while(p ->next->next != p) 30 { 31 cout<<p->next->elem<<" "; 32 p->next = p->next->next; 33 p = p->next; 34 } 35 cout<<endl; 36 cout<<p->next->elem<<" "<<p->elem<<endl; 37 break; 38 } 39 return 0; 40 }
解題思路二:使用set存儲,當set中元素的個數大於2個,執行循環,在循環中,需要每隔一個元素刪除一個,本次要回到頭開始有兩種情況:1、正好遍歷到最後一個,此時指向頭,再++,2、遍歷到最後一個的前一個,下一個從頭開始。刪除當前訪問的結點
 1 #include <iostream>
 2 #include <vector>
 3 #include <string>
 4 #include <algorithm>
 5 #include <set>
 6  
 7 int main()
 8 {
 9     using namespace std;
10     int n;
11     while (cin >> n) {
12         set<int> arr;
13         for (int i = 0; i < n; i++) {
14             arr.insert(i + 1);
15         }
16         set<int>::iterator iter = arr.begin();
17         iter++;
18         set<int>::iterator itor = iter;
19         while (arr.size() > 2) {
20             itor++;
21             if (itor == arr.end()) {
22                 itor = arr.begin();
23                 itor++;
24             }
25             else if (++itor == arr.end()) {
26                 itor = arr.begin();
27             }
28             if(arr.size() > 3)
29                 cout << *iter << " ";
30             else
31                 cout << *iter << endl;
32             arr.erase(*iter);
33             iter = itor;
34         }
35         if (iter == arr.begin()) {
36             cout << *arr.begin() << " " << *arr.rbegin() << endl;
37         }
38         else {
39             cout << *arr.rbegin() << " " << *arr.begin() << endl;
40         }
41     }
42     return 0;
43 }

1、誰是幸運兒--賽碼網周考(0609)