约瑟夫环
Description
n children are standing in a circle and playing the counting-out game. Children are numbered clockwise from 1 to n. In the beginning, the first child is considered the leader. The game is played in k steps. In the i-th step the leader counts out ai people in clockwise order, starting from the next person. The last one to be pointed at by the leader is eliminated, and the next player after him becomes the new leader.
For example, if there are children with numbers [8, 10, 13, 14, 16] currently in the circle, the leader is child 13 and ai = 12, then counting-out rhyme ends on child 16, who is eliminated. Child 8 becomes the leader.
You have to write a program which prints the number of the child to be eliminated on every step.
Input
The first line contains two integer numbers n and k (2 ≤ n ≤ 100, 1 ≤ k ≤ n - 1).
The next line contains k integer numbers a1, a2, ..., ak (1 ≤ ai ≤ 109).
Output
Print k numbers, the i-th one corresponds to the number of child to be eliminated at the i-th step;
题解:双向队列模拟,由于数比较大需要对m(队列元素的个数求余)
1 #include <iostream> 2 #include<stdio.h> 3 #include<string.h> 4 #include<deque> 5 using namespace std; 6 int a[5001]; 7 int main() 8 { 9 int i,j,b,p,m,n,k; 10 deque<int>s; 11 scanf("%d%d",&m,&n); 12 for(i=1; i<=n; i++) 13 scanf("%d",&a[i]); 14 for(i=1; i<=m; i++) 15 { 16 s.push_back(i); 17 } 18 for(i=1; i<=n; i++) 19 { 20 int count1=-1; 21 while(!s.empty()) 22 { 23 count1++; 24 if(count1==a[i]%m) 25 { 26 if(i==1) 27 printf("%d",s.front()); 28 else 29 printf(" %d",s.front()); 30 m--; 31 break; 32 } 33 s.push_back(s.front());//将栈顶元素压入队列尾 34 s.pop_front();//删除栈顶元素 35 } 36 37 s.pop_front(); 38 } 39 printf("\n"); 40 return 0; 41 }
本文来自博客园,作者:左手边五十米,转载请注明原文链接:https://www.cnblogs.com/moomcake/p/8646655.html