这水题,真的坑
测试数据最后有空行,如果用sc.hasNextLine()判断,会RE
要改为sc.hasNext()
搞了我一上午,烦死
import java.util.*;
public class POJ1591 {
static Scanner sc = new Scanner(System.in);
static int N=20;
static class Item{
int name;
Item next;
Item pre;
}
static Item first;
static Item last;
static int[] cards;
static void count(int total,int left){
if(total<=left){
Item item = first.next;
while (item!=null){
if(item.next!=null)
System.out.print(item.name+" ");
else
System.out.println(item.name);
item=item.next;
}
return;
}
int icard=0,card=0;
// 循环直到剩下left个人
while (total>left){
Item item=first.next;
card=cards[icard++];
while (item!=null){
//每次向前走cards[icard]步
int i;
for(i=1;i<card;i++){
if(item!=null)
item=item.next;
else
break;
}
if(i==card && item!=null) {
total--;
//删除第cards[cardi]个人
if (item.pre != null) {
item.pre.next = item.next;
}
if (item.next != null) {
item.next.pre = item.pre;
}
if (item == last)
last = item.pre;
item = item.next;
}
// 只剩left个人,输出结果
if(total==left){
item = first.next;
while (item!=null){
if(item.next!=null)
System.out.print(item.name+" ");
else
System.out.println(item.name);
item=item.next;
}
return;
}
}
}
}
static void run(){
// 构建链表
first = new Item();
first.next=first.pre=null;
first.name=Integer.MIN_VALUE;
last=first;
String[] s = sc.nextLine().split(" ");
// 总人数
int n=Integer.parseInt(s[0]);
// 可以回家的人数
int left = Integer.parseInt(s[1]);
cards = new int[N];
for(int i=1;i<=n;i++){
Item item = new Item();
item.name = i;
item.next = null;
item.pre = last;
last.next = item;
last=item;
}
// 初始化卡片数组
for(int i=2;i<s.length;i++){
cards[i-2]=Integer.parseInt(s[i]);
}
// 进入计算
count(n,left);
}
public static void main(String[] args) {
int so=1;
while (sc.hasNext()){
System.out.println("Selection #"+so);
run();
System.out.println();
so++;
}
}
}