본문 바로가기

IT/Algorithm

Algorithm: 요세푸스의 문제(Josephus Problem)

// Made by BAMU

#include <stdio.h>


void main(){


int person[100];

int sum, n;

int i,j,cnt1,cnt2;

i = 0;

j = 0;

cnt1 = 0;

cnt2 = 0;


printf("총 몇명입니까?");

scanf("%d",&sum);

printf("몇 번째 사람을 처형 시키시겠습니가? ");

scanf("%d",&n);





for(i=1; i<=sum; i++){                                                                                                 //person[0]은 사용하지 않습니다  

person[i] = 1;                                                                                                  //모든 person배열에 1을 대입

}


for(i=1; i<=sum; i++){

if( person[i] == 1 ) cnt1++;                                                                                 //1은 생존자, 0은 사망자를 뜻함

if( cnt1 == n){                                                                                                   //n번째 사람을 0으로 치환

person[i] = 0;

cnt1 = 0;                                                                                                  //다음 n번째 사람을 위해 초기화    

}

for(j=1; j<=sum; j++){

if(person[j] == 0) cnt2++;                                                                           //죽은 시람수를 계산

if(cnt2 == sum -1){                                                                                    //죽은 사람이 총 사람수보다 1명    

break;                                                                                             //작으면 생존자는 1명   

}

}


if(cnt2 == sum -1) break;                                                                                    //다른 연산으로 죽은 사람의 수가

                cnt2 = 0;                                                                                                          //바뀔수 있으므로 초기화                  if(i == sum) {                                                                                                    //반복을 위한 초기화

i = 0;

}


}

for(i=0; i<=sum; i++){

if( person[i] == 1 ) printf("%d번째 사람이 살아 남았습니다.\n",i);                            //생존자를 찾아 출력

}


}


[참고자료]

http://ko.wikipedia.org/wiki/%EC%9A%94%EC%84%B8%ED%91%B8%EC%8A%A4_%EC%88%9C%EC%97%B4