0,1,...n-1这n个数字排成一个圆圈,从数字0开始每次从这个圆圈里删除第m个数字,求出这个圆圈里剩下的最后一个数字。
#include <iostream> #include <list> 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 cur=numbers.begin(); while(numbers.size()>1) { for(i=1;i<m;i++) { cur++; if(cur==numbers.end()) cur=numbers.begin(); } list<int>::iterator next=++cur; if(next==numbers.end()) next=numbers.begin(); --cur; numbers.erase(cur); cur=next; } return *cur; } int main() { cout<<lastremaining(5,3); }
时间: 2024-10-26 06:55:32