CSES – Josephus Problem I

資料結構

#include<bits/stdc++.h>
#define int long long
#define pii pair<int,int>
#define f first
#define s second
#define fastio ios_base::sync_with_stdio(0);cin.tie(0)
using namespace std;
//declare
int n;
list<int> lst;
vector<list<int>::iterator> era;
//
signed main(){
    fastio;
    cin>>n;
    for(int i=n;i>=1;i--) lst.insert(lst.begin(),i);
    while(lst.size() > 1){
        era.clear();
        auto it = next(lst.begin());
        int sz = lst.size();
        for(int i=2;i<=sz;i+=2,advance(it,2)){
            era.push_back(it);
            cout<<*it<<" ";
        }
        for(int i=era.size()-1;i>=0;i--){
            lst.erase(era[i]);
        }
        if(sz % 2 == 1){
            lst.insert(lst.begin(), *prev(lst.end()));
            lst.erase(prev(lst.end()));
        }
    }
    cout<<*lst.begin()<<"\n";
    return 0;
}

相關文章

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *