我偶然发现了一个我似乎无法解决的USACO问题,而且似乎在每种情况下我都错了,我的程序似乎总是低估了解决方案的数量。问题陈述在这里(http://www.usaco.org/index.php?page=viewproblem2&cpid=714),但我可以提供它的较短版本
基本上,您会得到许多鸡和牛(n <= 20000),其中每只鸡的int值为x_n,每头牛的a_n和b_n的int值(不必区分) 您想要找到最大数量的鸡-牛对,其中一对的定义如下: a_n <= x_n <= b_n。鸡或牛配对后,就无法与其他人配对
我怎么了?
PriorityQueue<Integer> pqChicken = new PriorityQueue<Integer>();
PriorityQueue<State> pqCow = new PriorityQueue<State>();
//read in info for chicken and cow pq (not shown)
int ret = 0; //to record number of pairs
while (pqChicken.size() != 0 && pqCow.size() != 0) {
int chicken = pqChicken.peek();
State cow = pqCow.peek();
if (chicken < cow.low) { //all cows are above this chicken, it can't pair
pqChicken.poll();
} else if (chicken > cow.high) { //all chickens are above this cow, it can't pair
pqCow.poll();
} else { //it can pair, pair them and update the number of pairs
ret++;
pqChicken.poll();
pqCow.poll();
}
}
System.out.println(ret);
这是奶牛课:
static class State implements Comparable<State> {
int low,high; //low, high
public State(int low,int high) {
this.low=low;
this.high=high;
}
public int compareTo(State a) { //sort by decreasing low, then decreasing high
if (low > a.low)
return 1; //I think testing a case for equality won't matter
if (low == a.low && high > a.high)
return 1;
return -1;
}
}