最先,是自己用插入排序的方法做的,时间超出,没有通过。
代码如下:
import java.util.Scanner;
import java.util.Arrays;
public class BlackBox{
static int M, N;//这些变量必须是类变量
static int[] A,u;
public BlackBox(){//constructor
}
private void Input(){//get the inputs of M, N, A, and u
Scanner input=new Scanner(System.in);
M=input.nextInt();
N=input.nextInt();
A=new int[M+1];
u=new int[N+1];
int i;
for (i=1;i<=M;i++){
A[i]=input.nextInt();
}
for (i=1;i<=N;i++){
u[i]=input.nextInt();
}
input.close();
}
private void Do(){
int i=0;
for (int k=1;k<=M;k++){
InsertSort(A,1,k);
while(i<N&&u[i+1]==k){
i++;
System.out.println(A[i]);
}
}
}
private void InsertSort(int[] A, int a, int b){
int i=a;
while (i<b&&A[i]<=A[b]) i++;
if (i<b){
int temp=A[b];
for (int j=b-1; j>=i; j--){
A[j+1]=A[j];
}
A[i]=temp;
}
}
public static void main(String[] args){
BlackBox hi=new BlackBox();
hi.Input();
hi.Do();
}
}
后来,模仿大牛的代码,用一个大顶堆和一个小顶堆解决了问题。通过了。
代码如下:
import java.util.Arrays;
import java.util.Scanner;
public class BlackBox2{
static int M, N;//这些变量必须是类变量
static int[] A,u;
public BlackBox2(){//constructor
}
private void Input(){//get the inputs of M, N, A, and u
Scanner input=new Scanner(System.in);
M=input.nextInt();
N=input.nextInt();
A=new int[M+1];
u=new int[N+1];
int i;
for (i=1;i<=M;i++){
A[i]=input.nextInt();
}
for (i=1;i<=N;i++){
u[i]=input.nextInt();
}
input.close();
}
private void build1(int[] tree1, int k){//从下至上,变为大顶堆
int p=k;
while (p>1&&tree1[p]>tree1[p/2]){
int temp=tree1[p];
tree1[p]=tree1[p/2];
tree1[p/2]=temp;
p=p/2;
}
}
private void build2(int[] tree2, int k){//从下至上,变为小顶堆
int p=k;
while (p>1&&tree2[p]<tree2[p/2]){
int temp=tree2[p];
tree2[p]=tree2[p/2];
tree2[p/2]=temp;
p=p/2;
}
}
private void adapt1(int[] tree1, int k){
//从上至下,变为大顶堆
int p=1;
int son;
while(2*p<=k){
if (k==2*p||tree1[p*2]>=tree1[p*2+1])
son=p*2;
else
son=p*2+1;
if (tree1[p]<tree1[son]){
int temp=tree1[p];
tree1[p]=tree1[son];
tree1[son]=temp;
p=son;
}else
p=k;
}
}
private void adapt2(int[] tree2, int k){
//从上至下,变为小顶堆
int p=1;
int son;
while(2*p<=k){
if(k==2*p||tree2[p*2]<=tree2[p*2+1])
son=p*2;
else
son=p*2+1;
if (tree2[p]>tree2[son]){
int temp=tree2[p];
tree2[p]=tree2[son];
tree2[son]=temp;
p=son;
}else
p=k;
}
}
private void Do(){
int k=0;
int k1=0,k2=0;
int[] tree1=new int [M+1];
int[] tree2=new int [M+1];
for (int i=1; i<=N; i++){
int a=u[i];
for (int j=k+1;j<=a;j++){
tree2[++k2]=A[j];
build2(tree2,k2);
}
k=a;
tree1[++k1]=tree2[1];
build1(tree1,k1);
tree2[1]=tree2[k2--];
adapt2(tree2,k2);
while(k1!=0&&k2!=0&&tree1[1]>tree2[1]){
int temp=tree2[1];
tree2[1]=tree1[1];
tree1[1]=temp;
adapt1(tree1,k1);
adapt2(tree2,k2);
}
System.out.println(tree1[1]);
}
}
public static void main(String[] args){
BlackBox2 hi=new BlackBox2();
hi.Input();
hi.Do();
}
}