Happy PMP is freshman and he is learning about algorithmic problems. He enjoys playing algorithmic games a lot.
One of the seniors gave Happy PMP a nice game. He is given two permutations of numbers 1 through n and is asked to convert the first one to the second. In one move he can remove the last number from the permutation of numbers and inserts it back in an arbitrary position. He can either insert last number between any two consecutive numbers, or he can place it at the beginning of the permutation.
Happy PMP has an algorithm that solves the problem. But it is not fast enough. He wants to know the minimum number of moves to convert the first permutation to the second.
The first line contains a single integer n (1 ≤ n ≤ 2·105) — the quantity of the numbers in the both given permutations.
Next line contains n space-separated integers — the first permutation. Each number between 1 to n will appear in the permutation exactly once.
Next line describe the second permutation in the same format.
Print a single integer denoting the minimum number of moves required to convert the first permutation to the second.
3 3 2 1 1 2 3
2
5 1 2 3 4 5 1 5 2 3 4
1
5 1 5 2 3 4 1 2 3 4 5
3
In the first sample, he removes number 1 from end of the list and places it at the beginning. After that he takes number 2 and places it between 1 and 3.
In the second sample, he removes number 5 and inserts it after 1.
In the third sample, the sequence of changes are like this:
- 1 5 2 3 4
- 1 4 5 2 3
- 1 3 4 5 2
- 1 2 3 4 5
题解:
把第二个序列当做标准,比如1 4 5 2 3,那么1就是1,4就是2,5就是3这样处理一遍第一个序列,之后对处理后第一个序列求从第一个开始的最长的连续的上升序列,也就是从第一个开始已经按从小到大排好的数目,之后只要把没排好的往前插就好了,也就是n-该数目就是答案,一开始想成了最长上升子序列wa了一发
代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<queue>
#include<stack>
#include<math.h>
#include<vector>
#include<map>
#include<set>
#include<stdlib.h>
#include<cmath>
#include<string>
#include<algorithm>
#include<iostream>
#include<stdio.h>
using namespace std;
#define ll long long
int a[200005];
int num[200005];
int main()
{
int n,x,i,j,top;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&num[i]);
for(i=1;i<=n;i++)
{
scanf("%d",&x);
a[x]=i;
}
int nas=0;
for(i=0;i<n;i++)
{
num[i]=a[num[i]];
}
for(i=1;i<n;i++)
{
if(num[i]<num[i-1])
break;
}
printf("%d\n",n-i);
return 0;
}