链接:https://ac.nowcoder.com/acm/contest/12986/G
来源:牛客网
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 524288K,其他语言1048576K
64bit IO Format: %lld
G题Permutation
题目描述
You are given two permutations a and b of length n.
A permutation is a sequence of length n integers from 1 to n , in which all the numbers occur exactly once. For example, [1], [1,3,2], [3,1,5,2,4]
are permutations, and [2], [1,1] are not.
There are two types of operations as follow:
1.Remove the first integer in a . Then append any integer at the end of a .
2.Choose an ai (1≤i≤n) and modify it to any integer.
You have to find the minimum number of operations to make a and b
the same.
Be attention, you do not have to keep a in a permutation during the process.
输入描述:
The first line contains an integer n(1≤n≤10^6 ) — the length of a
and b .
The second line contains n integers a 1,a 2 ,…,a n (1≤a i ≤n) .The third line contains n integers b 1,b 2 ,…,b n (1≤b i ≤n) .
It is guaranteed that a and b are both permutations.
输出描述:
Output the minimum number of operations to make a and b the same.
示例1
输入
5
5 2 3 4 1
5 3 2 1 4
输出
3
说明
For the first example, there is a possible way:
- Remove the first integer in a and append 4, now a becomes [2,3,4,1,4].
- modify a 1 to 5, now a becomes [5,3,4,1,4] .
- modify a 3 to 2 , now a becomes [5,3,2,1,4]
So it only takes 3 operations to convert a into b .
思路:内容就是以最少次数将数组a->数组b。从文中可以看出有两种修改方式,一是将数组向前移动一格,并在尾部任意添加一个数字;二是任意修改数组中的一个数字。可以看出移动的效率值一定>=1,而修改只能是1。而且题目中明确指出数组中的数字是单一的,我们就可以利用下标位置找出移动效率最高的也就是次数最多的那个。
最终次数=需要移动步数+(总长度-需要移动步数-效率最高次数)<=>次数=总长度-效率最高次数
个人感觉有点贪心的思想。
正确代码:
#include<iostream>
#include<stdio.h>
#include<math.h>
#include<algorithm>
using namespace std;
long long a[1000005];
long long b[1000005];
int main(){
ios::sync_with_stdio(false);
int x,n;
while(cin>>n){
long long maxn=0;
b[0]=0;
for(int i=1;i<=n;i++){
cin>>x;
a[x]=i;
b[i]=0;
}
for(int i=1;i<=n;i++){
cin>>x;
if(a[x]-i>=0){
b[a[x]-i]++;
maxn=max(b[a[x]-i],maxn);
}
}
cout<<n-maxn<<endl;
}
return 0;
}