P1996 约瑟夫问题

 

P1996 约瑟夫问题

AC1

数据量少,暴力模拟 12ms

#include <iostream>
#include <algorithm>
#include <vector>
#include <cstdio>
using namespace std;

int main(){
    vector<int> ans;
    int personnum,number;
    scanf("%d%d",&personnum,&number);
    int nums[100];
    for (int i = 0; i < personnum; ++i) {
        nums[i]=i+1;
    }
    int flag = 0;
    int sum = 0;
    for (int j = 0; j < personnum; ++j) {
        if(nums[j]==0&&j==personnum-1){
            j=-1;
            continue;
        }
        if(nums[j]!=0&&j==personnum-1){
            flag++;
            if(flag%number==0){
                cout<<nums[j]<<" ";
                nums[j]=0;
                flag = 0;
                sum++;
            }
            j=-1;
            continue;
        }
        if(nums[j]==0)
            continue;
        flag++;
        if(flag%number==0){
            cout<<nums[j]<<" ";
            nums[j]=0;
            flag = 0;
            sum++;
        }
        if(sum==personnum)
            break;
    }
    return  0;
}

AC2 使用循环链表

也是12ms。。。

#include <iostream>
#include <algorithm>
#include <vector>
#include <cstdio>
#include <list>

using namespace std;
int main() {
    list<int> persons;
    int personnum, number;
    scanf("%d%d", &personnum, &number);
    for (int i = 0; i < personnum; ++i)
        persons.push_back(i + 1);
    int target = 0;
    for (list<int>::iterator it = persons.begin(); it != persons.end();) {
        target++;
        if (target == number) {
            cout << *it << " ";
            it = persons.erase(it);//这步易错
            target = 0;
        } else it++;
        if (it == persons.end())
            it = persons.begin();
        cout << (persons.begin() == persons.end());
        //3 6 9 2 7 1 8 5 10 4
    }
    return 0;
}
posted @ 2018-12-28 02:21  Sun2Q  阅读(171)  评论(0编辑  收藏  举报