poj3750约瑟夫环,循环队列

Description

有N个小孩围成一圈,给他们从1开始依次编号,现指定从第W个开始报数,报到第S个时,该小孩出列,然后从下一个小孩开始报数,仍是报到S个出列,如此重复下去,直到所有的小孩都出列(总人数不足S个时将循环报数),求小孩出列的顺序。
Input

第一行输入小孩的人数N(N<=64)
接下来每行输入一个小孩的名字(人名不超过15个字符)
最后一行输入W,S (W < N),用逗号”,”间隔
Output

按人名输出小孩按顺序出列的顺序,每行输出一个人名
Sample Input

5
Xiaoming
Xiaohua
Xiaowang
Zhangsan
Lisi
2,3
Sample Output

Zhangsan
Xiaohua
Xiaoming
Xiaowang
Lisi

import java.io.BufferedInputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;


public class Main {

        public static void main(String[] args) {

               Scanner cin = new Scanner( new BufferedInputStream(System.in) )  ;
               PrintWriter cout = new PrintWriter(System.out)  ;

               List<String> answer = new Solve(cin.nextInt() , cin).todo() ;

               for(String name : answer){
                     cout.println(name) ;
               }

               cout.flush() ; 
               cout.close() ;

        }




}

class Node{
      String name ;
      Node pre , next ;
      Node(){
           pre = next = null  ;
      }
}

class Solve{

      Node head ; 
      int  w  , s  ; 

      public Solve(int n , Scanner cin) {
             make(n) ;
             Node now = head ;
             for(int i = 1 ; i <= n ; i++){
                   now.name = cin.next() ;
                   now = now.next ;
             }
             String[] p = cin.next().split(",") ;
             w =  Integer.parseInt(p[0]) ; 
             s =  Integer.parseInt(p[1]) ; 
      } 

      void  make(int n){
            head = new Node() ;
            Node now = head ;
            for(int i = 1 ; i < n ; i++){
                  now.next = new Node() ;
                  now.next.pre = now ;
                  now = now.next ;
            }
            now.next = head ;
            head.pre = now ;
      }

      Node move(Node now , int step){
           for(int i = 1 ; i <= step ; i++) 
               now = now.next ;
           return now ;
      }  

      Node delete(Node now){
           now.next.pre = now.pre ;
           now.pre.next = now.next ;
           return now.next ; 
      }

      List<String>  todo(){

            List<String> answer = new ArrayList<String>() ; 

            Node now = move(head , w-1) ;
            while(now.next != now){
                  now = move(now, s-1) ;
                  answer.add(now.name) ;
                  now = delete(now) ;
            }
            answer.add(now.name) ;

            return answer ; 
      }

}

你可能感兴趣的:(poj3750约瑟夫环,循环队列)