题目描述:
做法:典型的约瑟夫环问题,只需要写一个循环链表模拟即可实现。
坑爹的地方:无
代码+注释:
/*Copyright :朝露の梦*/
#include <iostream> using namespace std; class Node{ public: Node* next; int monkey; Node(int mk, Node*rear){ monkey = mk; next = rear; } void operator=(Node* p){ monkey = p->monkey; next = p->next; } }; int main(){ int i, numofmonkey, M, txcase, j; cin >> txcase; while(txcase--){ cin >> numofmonkey >> M; Node* old = NULL;//用于储存要删除的节点 if(numofmonkey == 1) cout << 1 << endl; else{ Node* rear = new Node(1,rear); Node* current = rear; //初始化约瑟夫环 for(i = 2; i <= numofmonkey;i++){ current->next = new Node(i,rear); current = current->next; } current = rear; for(i = 0; i < numofmonkey -1;i++){ for(j = 1;j < M-1;j++){//这里j=1是为了让current移动到要删除的节点的前一个节点 current = current->next;//current指向要删除的节点的前一节点 } //删除操作 old = current->next; current->next = old->next; delete old; current = current->next;//继续往后移 } cout << current->monkey << endl;// } } system("pause"); return 0; }