1.链表写法:
#include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; typedef struct node{ int m; int id; struct node * next; }node; int main() { int t; cin >> t; while(t--){ int n, m; cin >> n; node *head=(node*)malloc(sizeof(node)); head->id = -1; node *cyclic=head; for(int i = 1; i <= n; i++){ node * body=(node*)malloc(sizeof(node)); cin >> body->m; body->id = i; body->next = NULL; cyclic->next=body; cyclic=cyclic->next; } cin >> m; int f = 0; int cnt = 0; // 报数 // while(f != n){ // cyclic = head->next; // for(int i = 1; i <= n; i++){ // if(cyclic->m != 0){ // 1退出 // cnt++; // if(cnt == m){ // f++; // m = cyclic->m; // cyclic->m = 0; // 1退出 // cnt = 0; // cout << i << " "; // } // } // cyclic = cyclic->next; // } // } cyclic->next=head->next; cyclic=head->next; while(f != n){ if(cyclic->m != 0){ cnt++; if(cnt == m){ f++; m = cyclic->m; cyclic->m = 0; // 1退出 cnt = 0; cout << cyclic->id << " "; } } cyclic = cyclic->next; } } return 0; } /* 1 6 2 5 3 7 5 4 3 out: 3 6 5 2 4 1 */
2.顺序存储写法:
#include <cstdio> #include <iostream> using namespace std; int a[105]; void f1(int m, int n){ int f = 0; int cnt = 0; // 报数 while(f != n){ for(int i = 1; i <= n; i++){ if(a[i] != 0){ // 1退出 cnt++; if(cnt == m){ f++; m = a[i]; a[i] = 0; // 1退出 cnt = 0; cout << i << " "; } } } } } int main(){ int t; cin >> t; while(t--){ int n, m; cin >> n; for(int i = 1; i <= n; i++){ cin >> a[i]; } cin >> m; f1(m, n); } return 0; }