排队合影(招商银行)
排队合影
https://ac.nowcoder.com/acm/contest/33182/A?&headNav=acm
通过 1……N 来对这N位同学进行标识,每一次调整都将某位同学向左移动若干个位置。请计算将同学们调整至目标顺序所需要的最少的调整次数。
输入:
5
5 1 3 2 4
4 5 2 1 3
输出:
2
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] a = new int[n];
int[] b = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
for (int i = 0; i < n; i++) {
b[i] = in.nextInt();
}
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < n; i++) {
map.put(b[i], i);
}
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = map.get(a[i]);
}
int temp = Integer.MAX_VALUE; //可省
int ii = 0; //可省
for(int i = 1; i < n; i++){ //可省
if(arr[i - 1] > arr[i]){ //可省
ii = i - 1; //可省
break; //可省
} //可省
} //可省
getMax(arr,n);
int flag = 0;
int tem = -1;
int t = n;
while (t > ii){ //可同上,换为 t > 0
int k = t;
tem = t;
t = hashMap1.get(k - 1);
flag += k - 1 - t;
}
System.out.println(flag);
}
static HashMap<Integer,Integer> hashMap1 = new HashMap<>();
public static void getMax(int[] a,int n){
int[] aa = new int[]{-1, Integer.MIN_VALUE};
for(int i = 0; i < n; i++){
if(a[i] > aa[1]){
hashMap1.put(i,i);
aa[0] = i;
aa[1] = a[i];
}else{
hashMap1.put(i,aa[0]);
}
}
}
}