アルゴリズム/データ構造/リンクリスト/ジョセファスの問題

ジョセファスの問題

24ページ.

N人が集団自殺しようとしていて,全員が円陣に並び,その円の中のM番目の人を処刑する.一人死ぬと円の大きさは1減る.処刑される順番を列挙.循環リストを利用.

josephus_problem.cpp

#include <iostream>
#include "Node.h"
using namespace std;
using namespace algo; 
/**
 * ジョセファスの問題
 * P.24
 */
void josephus_problem() {
  int N, M;
  Node<int> *t, *x;
  cout << "Enter the total number of people(N) : ";
  cin >> N;
  cout << "Who attempts suicide first?(M) : ";
  cin >> M;
  t = new Node<int>;
  t->key = 1;
  x = t;
  for (int i = 2; i <= N; i++) {
    t->next = new Node<int>;
    t = t->next;
    t->key = i;
  }
  t->next = x;
  cout << "The sequence of suicide is as follows : ";
  while (t != t->next) {
    for (int i = 1; i < M; i++) {
      t = t->next;
    }
    cout << t->next->key << " ";
    x = t->next;
    t->next = x->next;
    delete x;
  }	
  cout << t->key << endl;
}

実行結果

> Enter the total number of people(N) : 9 <Enter>
> Who attempts suicide first?(M) : 5 <Enter>
> The sequence of suicide is as follows : 5 1 7 4 3 6 9 2 > 8

Search

Apple Store(Japan)

Recommend

BUFFALO LinkStation RAID1対応 2.5インチHDD2ドライブ搭載 1.0TBモデル LS-WS1.0TGL/R1
¥ 39,332(新品)
1TBで3万台.さらに小型静音で
快適NAS生活が送れます.

view all

Twitter

Blog

Ads

ドミノ・ピザ 5%OFF!

 iTunes Store(Japan)

Logoole