zoukankan      html  css  js  c++  java
  • 约瑟夫环

    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("
    ");
    40     return 0;
    41 }
  • 相关阅读:
    good
    C# 调用控制台程序,并获取输出写入文件
    正则基础之——环视(Lookaround)
    C# 正则表达式及常用正则表达式
    c# winform 关于DataGridView的一些操作(很全,绝对够用)
    [bzoj4542][Hnoi2016]大数——同余+莫队
    [bzoj4010][HNOI2015]菜肴制作——拓扑排序
    [bzoj5285][Hnoi2018]寻宝游戏——思维+排序
    NOIP2018游记&&总结
    [bzoj5289][Hnoi2018]排列——贪心+堆
  • 原文地址:https://www.cnblogs.com/moomcake/p/8646655.html
Copyright © 2011-2022 走看看