圆圈中最后剩下的数字

来源:互联网 发布:ipad套子淘宝 编辑:程序博客网 时间:2024/05/23 17:36
/**圆圈中最后剩下的数字约瑟夫问题 last = (last + m)% i,其中i为元素的个数*/#include<bits/stdc++.h>using namespace std;int lastRemaining(unsigned int n, unsigned int m){    if(n<1 || m<1){        return -1;    }    unsigned int i=0;    list<int> numbers;    for(i=0; i<n; i++){        numbers.push_back(i);    }    list<int>::iterator current = numbers.begin();    while(numbers.size()>1){        for(int i=1; i<m; i++){            current++;            if(current == numbers.end()){                current = numbers.begin();            }        }        list<int>::iterator next = ++current;        if(next==numbers.end()){            next = numbers.begin();        }        --current;        numbers.erase(current);        current = next;    }    return *current;}//===================方法2==========================//递推公式 f(n) = (f(n-1) + m)%n n>1int lastRemaining_2(unsigned int n, unsigned int m){    if(n<1 || m<1){        return -1;    }    int last =0;    for(int i=2; i<=n; i++){        last = (last + m) % i;    }    return last;}