思路:每个优先级队列分别存储sell和buy,每个指令后都判断是否产生交易
package test;import java.util.Comparator;
import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;
import java.util.TreeSet;public class Test{ static class Com{static int id = -1;static {id++;}int q = 0; }static class Sell extends Com{int p,q;int sid = id; public Sell(int p, int q) {super();this.p = p;this.q = q;} }static class Buy extends Com{int p,q;int bid = id; public Buy(int p, int q) {super();this.p = p;this.q = q;} }public static void main(String[] args) {Comparator<Com> OrderIsdn = new Comparator<Com>(){@Overridepublic int compare(Com o1, Com o2) {if(o1.q < o2.q) return 1;return -1;}}; Queue<Sell> priorityQueue = new PriorityQueue<Sell>(100,OrderIsdn); Queue<Buy> priorityQueue2 = new PriorityQueue<Buy>(100,OrderIsdn); Scanner sc = new Scanner(System.in);String line = null;System.out.println("input:");while(!"".equals((line=sc.nextLine().toLowerCase()))){if(line.startsWith("buy")){int p = Integer.valueOf(line.substring(3, line.indexOf(" ")));int q = Integer.valueOf(line.substring(line.indexOf(" ")+1));priorityQueue2.add(new Buy(p, q));}else if(line.startsWith("sell")){int p = Integer.valueOf(line.substring(4, line.indexOf(" ")));int q = Integer.valueOf(line.substring(line.indexOf(" ")+1));priorityQueue.add(new Sell(p, q));}else if(line.startsWith("cancel")){int i = Integer.valueOf(line.substring(line.indexOf(" ")+1));boolean flag = false;for(Sell s:priorityQueue){if(s.sid==i){priorityQueue.remove(s);flag = true;break;}}if(!flag){for(Sell s:priorityQueue){if(s.sid==i){priorityQueue.remove(s);break;}}}}for(Iterator<Buy> buys = priorityQueue2.iterator();buys.hasNext();){Buy temp = buys.next();for(Iterator<Sell> sells = priorityQueue.iterator();sells.hasNext();){Sell s = sells.next();if(temp.q>=s.q){if(s.p >= temp.p){s.p -= temp.p; buys.remove();break;}else if(s.p < temp.p){temp.p -= s.p;sells.remove(); }}else{break;}}} } sc.close();}
}