1. 程式人生 > >vector實現約瑟夫

vector實現約瑟夫


/*
1.  讀入優化 的 初識、
約瑟夫實現  vector模擬實現
過程: 先將每個元素放入 容器中  push_back();    
       for遍歷將 n-1 個元素 在容器中刪除 第t個元素   a.erase(a.begin()+t);  
       最後容器中的最後一個元素就是活下來的人
*/
#include<iostream>
#include<stdio.h>
#include<string>
#include<string.h>
#include<algorithm>
#include<queue>
#include<stack>
#include<map>
#include<cmath>
#include<iomanip>
using namespace std;
typedef int _____I;
const int N=1e6+10;
const int INF=0x3f3f3f3f;
#define ERX(___I,__I,_I) for(_____I ___I = __I;___I <  _I; ___I++)
#define ERD(___I,__I,_I) for(_____I ___I = __I;___I <= _I; ___I++)
#define RED(___I,__I,_I) for(_____I ___I = __I;___I >= _I; ___I--)

/*
 定義一個int型 x f 
 定義一個char型得到一個字元
 如果該字元不是數字 則再判斷該字元是不是-號 如果是 就讓f變-1 得到ch
 如果該字元是數字就進行累計 x=x*10+ch-'0';ch=getchar();
 最後 返回總結果值  
*/
int read(){
 int x=0,f=1;char ch=getchar();
 while(ch<'0'||ch>'9'){if(ch=='-') f=-1;ch=getchar();}
 while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
 return x*f;
}
int n,m; //共n個人 每次隔m個人就去除此人 
vector<int> a;
int main(){
 n=read();m=read();
 for(int i=1;i<=n;i++)
  a.push_back(i);
 int t=0;
 cout<<"依次需要刪除的點:"<<endl;
 for(int i=1;i<n;i++){
  t=(t+m-1)%a.size();//元素下標是從0開始 因此要減一
  cout<<a[t]<<endl;
  a.erase(a.begin()+t);
 }
 cout<<endl<<endl;
 for(int i=0;i<a.size();i++) cout<<a[i]<<endl; //最後只剩餘一個 
 return 0;
}