文章

33

粉丝

0

获赞

139

访问

3.9k

头像
猴子报数 题解:根据题意模拟(约瑟夫环)
P1081 兰州大学/湖南大学机试题
发布于2026年3月12日 13:28
阅读数 174

#include<bits/stdc++.h>

using namespace std;


int main(){

int n;
int s,m;

while(1){
cin>>n>>s>>m;
if(n==0 && s==0 && m==0) break;

list<int> lst;
for(int i=1;i<=n;i++) lst.push_back(i);  //初始化list

auto it = lst.begin();
advance(it,s-1);//移动到指定的第s个位置

	while(!lst.empty()){//输出当前list所有数据之前一直循环
		
		for(int i=1;i<m;i++){  //it-->第m个猴子
			it++;
		if(it==lst.end()) it = lst.begin();
		}
		
		
		cout<<*it;
		it = lst.erase(it);
		/***
		假设链表初始状态和it位置:
		链表: 1 → 2 → 3 → 4 → 5
					  ↑
					  it
		执行it = lst.erase(it)后:
		1. 删除3
		2. 链表变为: 1 → 2 → 4 → 5
		3. erase()返回指向4的迭代器
		4. it被赋值为指向4

		链表: 1 → 2 → 4 → 5
					  ↑
					  it
		***/
		
		if(!lst.empty()) cout<<",";
		//如上所示,如果it指向最后一个,那么擦除后it为空,则回到开头.
		if(it == lst.end()) it = lst.begin();
		}
		cout<<endl;		
	}
	
	
		
return 0;
}

 

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发