P1145 约瑟夫

思路: 用链表进行模拟。

1.不用STL

#include <iostream>
using namespace std;

struct Node{
    int n;
    Node *next;
};
long n,m;

Node *head,*p,*r;
int main(){
    cin >> n >> m;
    head = new Node;
    head->n = 1;
    head->next = NULL;
    r = head;
    for(int i=2;i<=n;++i){
        p = new Node;
        p->n = i;
        p->next = NULL;
        r->next = p;
        r = p;
    }
    r->next = head;
    r = head;
    if(m != 1){
        for(int i=0;i<n;++i){
            for(int j=0;j<m-2;++j){
                r = r->next;
            }
            cout << r->next->n << " ";
            p = r->next;
            r->next = r->next->next;
            r = r->next;
            delete p;
        }        
    }else{
        for(int i=0;i<n;++i){
            cout << r->n << " ";
            p = r;
            r = r->next;
            delete p;
        }
    }
    cout << endl;
    return 0;
}

 

2. 使用STL

#include <iostream>
#include <list>
using namespace std;
long n,m;
list<int> l;
int main() {
    cin >> n >> m;
    if(n<0 && m<0) {
        return 0;
    }
    for(int i=1; i<=n; ++i) {
        l.push_back(i);
    }
    list<int>::iterator beg = l.begin();
    for(int i=0; i<n; ++i) {
        for(int j=1; j<m; ++j) {
            beg++;
            if(beg == l.end()) {
                beg = l.begin();//因为List内容不断变化,所以应该重新获取一次R。
            }
        }
        cout << *beg << " ";
        beg = l.erase(beg);
        if(beg == l.end()) {
            beg = l.begin();//因为List内容不断变化,所以应该重新获取一次R。
        }    
    }
    cout << endl;
    return 0;
}

 

 
posted @ 2019-02-25 21:34  zz2108828  阅读(327)  评论(0编辑  收藏  举报