zoukankan      html  css  js  c++  java
  • Java解决小孩围圈问题

    问题描述:一堆小孩围成一个圈,从第一个小孩开始数,每数到第三个便把第三个孩子删去,数到只剩一个小孩为止,并求该孩子的具体编号。

    解决办法

    1.

    package test;
    public class Compare {
        public static void main(String[] args) {
        boolean[] array=new boolean[500];
        for(int i=0;i<array.length;i++) {
            array[i]=true;
        }
        int leftcount = 500;
        int countnum = 0;
        int index = 0;
        
        while(leftcount > 1) {
            if(array[index]) {
             countnum ++;
                if(countnum == 3) {
                countnum = 0;
                array[index] = false;
                leftcount--;
                }
            }
            index ++;
            if(index == 500) {
                index = 0;
            }    
        }
         for(int i=0;i<array.length;i++) {
            if(array[i]) {
            System.out.println(i);
            }
         }
         }
        
    }

    2.

    package test;
    
    public class Studentcircle {
      public static void main(String[] args) {
          makecircle b=new makecircle(500);
          int countnum=0;
          student m=b.first;
          while(b.count>1) {
             countnum++;
             if(countnum==3) {
                 countnum=0;
                 b.delete(m);
             }
             m=m.right;
          }
          System.out.println(b.first.id);
      }
      
    }
    class student{
       int id;
       student left;
       student right;
    }
    class makecircle{
        int count=0;
        student first,last;
        makecircle(int n){
         for(int i=0;i<n;i++) {
            add();
         }
        }
        void add() {
          student x= new student();
          x.id=count;
          if(count<=0) {
             first=x;
             last=x;
             x.left=x;
             x.right=x;
          }else {
             last.right=x;
             x.left=last;
             x.right=first;
             first.left=x;
             last=x;
           }
          count++;
        }
        void delete(student x) {
            if(count<=0) {
            return;
            }else if(count==1) {
                first=last=null;
             }else {
                x.left.right=x.right;
                x.right.left=x.left;
           
              if(x==first) {
                 first=x.right;  
              }else if(x==last) {
                  last=x.left;
              }
             } 
            count --;
        }
        
    }

  • 相关阅读:
    Selenium之编辑框操作
    Selenium之勾选框操作
    Selenium之单选框操作
    [复习资料]组合计数学习笔记
    ARC104游记
    [被踩计划] 题解 [省选联考 2020 A 卷] 作业题
    题解 [SEERC2019]Game on a Tree
    [被踩计划] 题解 [NOI2020]美食家
    [被踩计划] 题解 [省选联考 2020 A 卷] 组合数问题
    [被踩计划] 题解 括号树
  • 原文地址:https://www.cnblogs.com/frankzone/p/8098395.html
Copyright © 2011-2022 走看看