您的位置:首页 > 其它

约瑟夫问题

2014-11-04 00:40 260 查看
// sum个猴子 , num为查数 , 求出最后的猴王

// 我用c写的简单实现

#include <stdio.h>

int main( void )

{

int arr[100]; // sum <= 99

int sum , num, count , count2 , i;

scanf("%d%d" , &sum , &num);

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

arr[i] = i;

count = sum ;

while( count != 1 )

{

count2 = 0;

while( 1 )

{

while( arr[ i ] == 0 )

{

i++;

if( i == sum + 1 ) i =1;

}

count2++;

if( count2 == num )

break;

i++;

if( i == sum + 1 ) i =1;

}

arr[ i ] = 0;

count--;

}

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

if( arr[ i ] ! = 0 )

printf( "King is %d" , i);

return 0;

}

//输入 6 2

//输出 5

//输入 12 4

//输出 1

#include <stdio.h>

#include <stdlib.h>

typedef struct Node {

int n;

struct Node * next ;

}* pNode ,Node;

int main( void )

{

int sum , num , i , count ;

pNode head , temp,temp2;

scanf( "%d%d" , &sum , &num );

if ( num == 1 )

{

printf( "%d",sum);

return 0;

}

i = 0;

temp = head = NULL;

while ( i != sum )

{

if (head == NULL )

{

head = ( pNode ) malloc ( sizeof( Node ) );

head->n = ++i ;

head->next = NULL;

temp = head;

}

else

{

temp2 = ( pNode ) malloc ( sizeof( Node ) );

temp2->n = ++i;

temp2->next = NULL;

temp ->next = temp2;

temp = temp->next;

}

}

temp ->next = head;

temp = head;

i = 0;

while ( i++ != sum - 1)

{

count = num - 2;

while ( count--)

temp = temp ->next;

temp->next = temp->next->next;

temp = temp->next;

}

// head = temp

printf("%d\n",temp->n);

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: