Permutations

来源:互联网 发布:arch linux安装教程 编辑:程序博客网 时间:2024/06/01 10:49

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 
Input 

3 2 1 
1 2 3 
Output 

Input 

1 2 3 4 5 
1 5 2 3 4 
Output 

Input 

1 5 2 3 4 
1 2 3 4 5 
Output 

3

这道题的大概意思是把最后一个元素不断地往前移动数据,将第一个数据得到第二个数据所用的最少的步数

下面是很奇妙的算法,很难想到,不过懂了之后却很简单

#include <stdio.h>
int main()
{
    int n, a[200010], b[200010], i, j, k, flag;
    scanf("%d", &n);
    k = -1;
    for(i = 0; i < n; i++)
        scanf("%d", &a[i]);
    for(i = 0; i < n; i++)
        scanf("%d", &b[i]);


    for(i = 0; i < n; i++)
    {
        flag = 0;
        for(j = k + 1; j < n; j++)
        {
            if(a[i] == b[j])
            {
                flag = 1;
                k = j;
                break;
            }
        }
        if(!flag)
            break;
    }
    printf("%d\n", n - i);
}

找张纸模拟一下大概就懂了!!!

a[i] == b[j]则说明这个数可以不用移动或者可以通过被其他数主动移动而被动的移动到自己该处在的位置,如果不想等,那么说明他所处的位置在自己应该处的位置的后边,那就必须前移。

0 0
原创粉丝点击