poj3750-小孩報數問題(約瑟夫環),poj3750-報數
一,題意:
中文題。
二,思路:
1,輸入。
2,無限循環1~n~1~n,直到輸出n次,再跳出。
3,輸出名字,並標記。
普通模擬版:

![]()
1 #include<iostream>
2 #include<cstring>
3 using namespace std;
4 int main() {
5 char name[56][16];
6 int n, w, s;
7 cin >> n;
8 for (int i = 1; i <= n; i++) {
9 cin >> name[i];
10 }
11 scanf("%d,%d", &w, &s);
12 int count = 0; //記錄經過未標記的名字幾次
13 int k = 0; //記錄輸出的次數
14 for (int i = w; k!=n ; i++) { //輸出 n 次,跳出
15 if (i > n) i = i % n; //循環 1~n~1~n
16 if (strcmp(name[i], "1")) count++; //經過未標記的名字時 count++
17 if (count == s) { //經過s次未被標記的名字時
18 cout << name[i] << endl;
19 k++; //輸出一次 k++
20 count = 0; //輸出以後count重新記數
21 w = i; //輸出之後,w 重新從 i 開始
22 strcpy(name[i], "1"); //已經輸出的名字標記為 1
23 }
24 }
25 return 0;
26 }
View Code
線性表模擬版:

![]()
1 #include<iostream>
2 #include<string>
3 using namespace std;
4
5 class SeqList {
6 public:
7 SeqList(string str[], int n); //構造函數,創建長度為n 的線性表
8 string Delete(int i); //輸出並刪除結點
9 int getLength() { return length; } //獲取長度
10 private:
11 int length;
12 string name[65];
13 };
14
15 SeqList::SeqList(string str[], int n) { //實現構造函數
16 for (int i = 0; i < n; i++) {
17 name[i] = str[i];
18 }
19 length = n;
20 }
21
22 string SeqList::Delete(int i) {
23 string x = name[i - 1]; //定義一個x接收被刪除的字符串
24 for (int j = i; j < length; j++) { //從被刪除的結點開始,後面的向前移動,覆蓋被刪除的結點
25 name[j - 1] = name[j];
26 }
27 length--; //刪除一個結點,長度減 1
28 return x;
29 }
30
31 int main() {
32 string str[65];
33 int n, w, s;
34 cin >> n;
35 for (int i = 0; i < n; i++) {
36 cin >> str[i];
37 }
38 scanf("%d,%d", &w, &s);
39 SeqList S(str, n);
40 while(n--) {
41 int ans = (w + s - 1); //ans 表示要輸出的名字的序號
42 if ( ans==S.getLength() ) {
43 w = ans;
44 cout << S.Delete(w) << endl;
45 }
46 else {
47 if (ans % S.getLength() != 0) {
48 w = ans % S.getLength();
49 cout << S.Delete(w) << endl;
50 }
51 else {
52 cout << S.Delete(w--) << endl;
53 }
54
55 }
56
57 }
58 return 0;
59 }
View Code
版權聲明:本文為博主原創文章,未經博主允許不得轉載。