POJ2259 Team Queue (JAVA)
第一次TLE,对每个group重新设置Queue中定位,定位到每个group的最后一个元素,但WA
经过检查,DEQUEUE时没有根据情况重新计算group,插入时没有根据情况重新给last赋值
贴AC代码
import java.util.*; public class POJ2259 { static class Member{ String value; int group; //因为更新group数组会用到pre,所以得做一个双向链表 Member next; Member pre; public Member(String value, int group, Member next,Member pre) { this.value = value; this.group = group; this.pre = pre; this.next = next; } } static Map<String,Member> members;//根据元素名称获取元素对象,用散列比较快 static Scanner sc = new Scanner(System.in); static Member first;//列表头 static Member last;//列表尾 static Member[] gindicator;//记录每个group最后一个元素在列表中的位置 static void doQueueOp(){ String[] s=sc.nextLine().split(" "); while (!s[0].equals("STOP")){ if(s.length==2){ // ENQUEUE x //首先根据元素名称获取元素对象 String name = s[1]; Member m = members.get(name); //检查团队中是否已经有队友在队列中 int group = m.group; //没有队友在队列中,排在队列最后 if(gindicator[group]==null){ gindicator[group]=m; //要记得更新last last.next=m; m.next=null; m.pre=last; last=m; } //有队友,排在团队最后一个队友最后 //gindicator[groupid]记录了团队最后一个队友的位置,所以直接排在group[groupid]后面就行 else { m.next=gindicator[group].next; if(gindicator[group].next!=null){ gindicator[group].next.pre=m; } m.pre=gindicator[group]; gindicator[group].next=m; //如果队友正好是队列最后一个,需要更新last if(last==gindicator[group]){ last=m; } gindicator[group]=m; } } //DEQUEUE else { //如果队列不空,删除队列第一个元素 if(first.next!=null) { Member m = first.next; first.next = m.next; if(m.next != null){ m.next.pre=first; } //如果队列只有一个元素,需要更新last if(last==m){ last=m.pre; } //要记得更新gindicator if(gindicator[m.group]==m){ //如果m是团队中唯一一个元素,把gindicator[groupid]置空 if(m.pre==null) { gindicator[m.group] = null; } //否则把gindicator[groupid]置为m的前一个队友 //这里需要用到m.pre,所以做双向链表 else { if(m.pre.group==m.group){ gindicator[m.group]=m.pre; }else { gindicator[m.group] = null; } } } System.out.println(m.value); } } s=sc.nextLine().split(" "); } } public static void main(String[] args) { int n = Integer.parseInt(sc.nextLine()); int so=1; while (n != 0){ members = new HashMap<String,Member>(); //根据元素名称散列 for(int i=0;i<n;i++){ String[] s = sc.nextLine().split(" +|,"); for(int j=1;j<s.length;j++){ String name = s[j]; Member m = new Member(name,i,null,null); members.put(name,m); } } gindicator = new Member[n]; first = new Member("-1",-1,null,null); last = first; System.out.println("Scenario #"+so); doQueueOp(); System.out.println(); so++; n = Integer.parseInt(sc.nextLine()); } } }