合唱队
描述 |
计算最少出列多少位同学,使得剩下的同学排成合唱队形 说明: N位同学站成一排,音乐老师要请其中的(N-K)位同学出列,使得剩下的K位同学排成合唱队形。 |
---|---|
知识点 | 循环 |
运行时间限制 | 0M |
内存限制 | 0 |
输入 |
整数N 一行整数,空格隔开,N位同学身高 |
输出 |
最少需要几位同学出列 |
样例输入 | 8 186 186 150 200 160 130 197 200 |
样例输出 | 4 |
提示:这个题需要最长递增序列的知识
代码如下:
import java.util.Scanner; public class Main { public static int listUp(int[] data,int low,int high){ int n = high-low+1; int[] f = new int[n]; f[0] = 1; for(int i = low+1;i <= high; i++){ f[i-low] = 1; for(int j = low;j < i;j++) if(data[j]<data[i]&&f[j]>f[i]-1) f[i] = f[j]+1; } // for(int tmp:f) // System.out.print(tmp); return f[n-1]; } public static int listDown(int[] data,int low,int high){ int n = high-low+1; //System.out.println(" low: "+low+" high: "+high+" n: "+n); int[] f = new int[n]; f[0] = 1; for(int i = low+1;i <= high; i++){ f[i-low] = 1; for(int j = low;j < i;j++) if(data[j]>data[i]&&f[j-low]>f[i-low]-1) f[i-low] = f[j-low]+1; } int max = f[0]; for(int tmp:f) if(max<tmp) max = tmp; //System.out.println(" f.length: "+f.length); return max; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int num = in.nextInt(); int data[] = new int[num]; int result[] = new int[num]; for(int i = 0;i < num; i++){ data[i] = in.nextInt(); result[i] = 0; } //System.out.println(listDown(data,2,8)); for(int i = 0;i < data.length-1; i++){ //System.out.println(i+" "+data.length); result[i] += listUp(data,0,i); //System.out.println("result from 0 to "+i+" is "+result[i]); result[i] += listDown(data,i+1,data.length-1); //System.out.println("result2 from "+(i+1)+" to "+(data.length-1)+" is "+result[i]); } int max = 0; for(int tmp:result) if(tmp>max) max = tmp; System.out.println(data.length-max); // listDown(data,0,data.length-1); // System.out.println(); // listUp(data,0,data.length-1); } }