您的位置:首页 > 产品设计 > UI/UE

uva 133 - The Dole Queue|java实现

2014-08-01 23:19 489 查看
题意:所有n个人围成一个圈,一边从1号开始逆时针数k个,出局;一边从n号开始顺时针数m个,出局。两个同时发生。如果这两个数到同一个人,就这个人出局。

分析:其实就是一个双向链表,从两边同时开始数,注意是同时,说是同时,但是程序里面必然有处理的先后。我们可以先处理正着数的,然后处理倒着数的。但是这样处理有一个情况就是,当要处理的两个人相邻,这时,要同时处理,也就是同时去除这两个人(否则先处理其中一个,那么这个的指针会指到本该同时被处理的人身上)

public class Person {
int num;
Person pre=null;
Person next = null;

public Person(int num) {
this.num = num;
}
}

public class Circle {
Person head;
int size =0;
public Circle() {
this.head = new Person(0);
}

Person getFirst(){
return head.next;
}

Person getLast(){
return head.next.pre;
}

void add(Person person){
if(size==0){
head.next = person;
person.pre = person;
person.next = person;
}else{
head.next.pre.next = person;
person.pre = head.next.pre;
person.next = head.next;
head.next.pre = person;
}
size++;
}

void delete(Person person){

}
}


import java.io.IOException;
import java.util.LinkedList;
import java.util.Scanner;

public class Test {

public static void main(String[] args) throws IOException {
int n = 7;//总人数
int k = 2;//正着数
int m =3;//倒着数
Circle circle = new Circle();
//装载数据
for(int i=0;i<n;i++){
circle.add(new Person(i+1));
}

int step1=0;
int step2=0;
Person first = circle.getFirst();
Person last = circle.getLast();
int count=0;
//开始两端同时数数
while(circle.size!=0){//剩下一个人才结束
step1++;
step2++;
if(step1 == k && step2 == m &&first.num == last.num){//如果数到同一个
step1=1;
step2=1;
first.next.pre = last.pre;
last.pre.next = first.next;
circle.size--;
System.out.println(first.num+"同时出局");
first = first.next;
last = last.pre;
}

if(step1 == k && step2 == m && first.next.num == last.num){//同时删除,而且这个两个人相邻
step1=1;
step2=1;
first.pre.next = last.next;
last.next.pre = first.pre;
circle.size = circle.size-2;
System.out.println(first.num+"整除"+k+"出局,同时"+last.num+"整除"+m+"出局");
first = first.next.next;
last = last.pre.pre;
}else{
if(step1 == k){
step1=1;
first.next.pre = first.pre;
first.pre.next = first.next;
circle.size--;
System.out.println(first.num+"整除"+k+"出局");
first = first.next;
}

if(step2 == m){
step2=1;
last.next.pre = first.pre;
last.pre.next = first.next;
circle.size--;
System.out.println(last.num+"整除"+m+"出局");
last = last.pre;
}
}
first = first.next;
last = last.pre;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: