zoukankan      html  css  js  c++  java
  • 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;
    }
     
  • 相关阅读:
    [转]趣题:一个n位数平均有多少个单调区间?---- From Matrix67
    2015编程之美复赛
    Codeforces Round #304 (Div. 2)
    HDU 5226
    HDU 5225
    HDU 3666
    HDU 4598
    Codeforces Round #303 (Div. 2) E
    编程之美初赛第二场AB
    2015 编程之美初赛第一场 AC题
  • 原文地址:https://www.cnblogs.com/--zz/p/10433651.html
Copyright © 2011-2022 走看看