ZOJ FatMouse’s Speed
这题目一看就知道是LIS的加强版,判断两个方向。
思路:由于题目不像LIS直接检索递增,所以有了预处理。
这里我根据老鼠的重量排序,质量相等就按速度逆序排序。
然后再对速度进行LIS的处理就好了。
然后另一个坑就是还得输出任意最长序列,那么我新建一个数组front[n]去记录这个值的最长子序列的上一个值的索引就ok了
例如:front[j] = i; 就表示 j 的上一个为 i
还有另一种做法就是在类(Mouse)里面多加个属性值,front, 并令front = 上一个值也可以 这里就不展示了,,原理一样
解决了这些问题就挺简单的了
然后附上代码吧:
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
class Mouse implements Comparator<Mouse>{
public int weight;
public int speed;
public int index;
public int compare(Mouse o1, Mouse o2) {
if(o1.weight == o2.weight)
return o2.speed - o1.speed;
else
return o1.weight - o2.weight;
}
}
public class FatMouseSpeed {
static Mouse[] mouse = new Mouse[10005];
static int[] front = new int[10005];
static int[] dp = new int[10005];
public static void process(int n) { //预处理数组
for(int i = 0; i < n; i++)
front[i] = -1;
}
/* public static void display(int n) { //测试函数
for(int i = 0 ; i < n; i++) {
System.out.print(mouse[i].weight+" ");
System.out.print(mouse[i].speed+" ");
System.out.print(mouse[i].index+" ");
System.out.println();
}
}
*/
/* public static void display1(int n) { //测试函数
for(int i = 0 ; i < n; i++) {
System.out.print(dp[i]+" ");
}
System.out.println();
}
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int len = 0;
while(sc.hasNext()) {
mouse[len] = new Mouse();
mouse[len].weight = sc.nextInt();
mouse[len].speed = sc.nextInt();
mouse[len].index = len;
len++;
}
Mouse m = new Mouse();
Arrays.sort(mouse, 0, len, m); //排序
//display(len);
process(len);
dp[len-1] = 1;
int lastIndex = -1;
int res = 0;
for(int i = len-2; i >= 0; i--) {
int l = 0;
for(int j = len-1; j > i; j--) { //这里跟LIS一样,多了个比较而已。
if(mouse[i].weight < mouse[j].weight && mouse[i].speed > mouse[j].speed && l < dp[j]) {
l = dp[j];
front[i] = j;
}
}
dp[i] = l + 1;
if(dp[i] > res) {
res = dp[i];
lastIndex = i;
}
}
//display1(len);
System.out.println(res); //输出长度
//System.out.println(lastIndex);
while(lastIndex != -1) { //输出序列
System.out.println(mouse[lastIndex].index+1);
lastIndex = front[lastIndex];
}
}
}