Description
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.
Input
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.
Output
Print a single integer denoting the minimum number of moves required to convert the first permutation to the second.
Sample Input
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
这是暑假集训AC的第一道题目,按Vjudge里的显示,貌似是CF里面的一道题,题意很好理解,两个无序数列,将其中一个完全变换成第二个,最少需要多少步。
但是实际操作起来,就不知道从何下手,后来找李忠显大神问思路,学长的思想果然很有针对性,他给我讲了一种转换方法,因为两个数列都是随机无序,别说是用计算机了,自己手动去插来插去都觉得没什么固定的方法可寻觅。
所以李大神的很棒的思路就是,给目标序列强制排序,这些名词是我自己定义的,也就是说,不管目标序列里的数字有多乱,我反正按数组下标,强制把目标序列定义为有序数列,比如说1 5 2 3 4,我就反正按数组下标,1就对应第一,5就对应第二。。。然后回到原序列,1 2 3 4 5,根据我们自己定义的排序规则,即按照目标序列排序法,它的排序后的数列应该是 1 3 4 5 2.。。而且这个题目故意说每次只能挑选最后一位数字对序列任意一位进行插入,其实是降低了难度,因为我规定了目标序列是有序数列,其他数列就都得按照目标数列为标准看齐,所以,题目的要求这时候就变成 只要原序列转化出来的新数列是按升序排列,即可,也就是说,求出新数列的最长上升子序列,。。剩下的数字肯定需要通过插入到前方有序数列。。。因此,只要求出最长上升子序列的长度,剩下了多少数字,那就需要插几次。。。原题立解!
简单的总结这种思想,就是自定义规则,我不管目标序列有多乱,我就以他为标准,我就认可他是上升的序列,然后其他序列都得按照他的标准来排序。。。这样就行了。。所以弄ACM思想绝对不能僵化,各种需要打破常规思维。
#include <cstdio> #include <iostream> #define maxn 200005 int source[maxn]; int aim[maxn]; int temp[maxn]; int main() { int n,node; scanf("%d",&n); for (int k=1;k<=n;k++) scanf("%d",&source[k]); for (int q=1;q<=n;q++) { scanf("%d",&node); aim[node]=q; //这里没有按常规读,反而是把读进来的数字做下标,当前下标做数组的内容,这样这个数组就成了转换器,给个原序列数字就能帮我转化成新规则下的数字 } for (int i=1;i<=n;i++) { temp[i]=aim[source[i]]; //temp数组存的就是按照新规则转化出来的序列。 } int j; for (j=2;j<=n;j++) { if (temp[j-1]>temp[j]) break; } printf("%d ",n-j+1); return 0; }