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 }
  • 相关阅读:
    Redis
    cz_health_day13项目实战
    cz_health_day11
    cz_health_day10
    cz_health_day09
    cz_health_day08
    MySQL8管理系列之二:从5.5升级到8的问题处理
    MySQL8管理系列之一:Mysql 8.0以后版本的安装
    MySQL 5.5.x 数据库导入到 8.0.x 服务器
    修改Mysql 8.0版本的默认数据库目录
  • 原文地址:https://www.cnblogs.com/moomcake/p/8646655.html
Copyright © 2011-2022 走看看