zoukankan      html  css  js  c++  java
  • 数据结构—约瑟夫环

    约瑟夫环

    是一个数学的应用问题:已知n个人(以编号1,2,3…n分别表示)围坐在一张圆桌周围。从编号为k的人开始报数,数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;依此规律重复下去,直到圆桌周围的人全部出列。通常解决这类问题时我们把编号从0~n-1,最后结果+1即为原问题的解。

    约瑟夫环运作如下:

    1、一群人围在一起坐成环状(如:N)
    2、从某个编号开始报数(如:K)
    3、数到某个数(如:M)的时候,此人出列,下一个人重新报数
    4、一直循环,直到所有人出列,约瑟夫环结束

    代码实现 :

    #include <queue>
    #include <cstdio>
    #include <cstring>
    #include <iostream>
    #include <algorithm>
    
    using namespace std;
    
    typedef struct node{
    	int date;
    	bool flag;
    	struct node* nxt;
    }node,*linklist;
    
    void slove(int n,int m,int k) {
    	
    	linklist s ,tmp ;
    	tmp = new node;
    	tmp->date = 1; tmp->flag = false;
    	tmp->nxt = tmp; s = tmp;
    	for (int i = 2 ; i <= n ; i++ ) {
    		tmp = new node;
    		tmp->date = i; tmp->flag = false;
    		tmp->nxt = s->nxt; s->nxt = tmp;
    		s = tmp;
    	} s = s->nxt;
    	
    	for (int i = 1;i<=n;i++) {
    		if ( s->date == k ) break;
    		s = s->nxt;
    	}
    	queue<int>que;
    	int cnt = 0 ,count = 0;
    	while( cnt < n ) {
    		if ( !s->flag ) {
    			count++;
    			if ( count % m == 0 ) {
    				cnt++; s->flag =true;
    				que.push(s->date);
    			}
    		}
    		s = s->nxt;
    		
    	}
    	printf("The ans is :");
    	while(!que.empty()) {
    		printf("%d ",que.front()); que.pop();
    	} puts("");
    }
    
    int main() {
    	
    	int n ,m ,k ,choose;
    	while( 1 ) {
    		printf("请输入 人数--倍数--开始的位置(空格隔开) :
    ");
    		cin >> n >> m >> k; 
    		slove(n ,m ,k );
    		printf("您还需要继续吗(1.继续,0.停止):
    ");
    		cin >> choose;
    		if(!choose) break;
    	}
    	return 0;
    }
    
  • 相关阅读:
    hdu_5750_Dertouzos(线性筛)
    hdu_5748_Bellovin(LIS)
    Codeforces Round #364 (Div. 2) C.They Are Everywhere
    Codeforces Round #364 (Div. 2) D. As Fast As Possible
    [BZOJ 2456]Mode(神奇的抵销)
    [poj3046]Ant Counting(母函数)
    [poj1742]coin
    [poj3666]Making the Grade(DP/左偏树)
    【POJ各种模板汇总】(写在逆风省选前)(不断更新中)
    [USACO2004][poj1989]The Cow Lineup(乱搞)
  • 原文地址:https://www.cnblogs.com/Nlifea/p/11745928.html
Copyright © 2011-2022 走看看