#ZOJ FatMouse's Speed
阿新 • • 發佈:2018-12-02
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];
}
}
}