training@USC permutation

Permutation

Time Limit:1000ms    Memery Limit:32768K

Accepted/Submit(Users):  1/1(100.0%)

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

There are almost five test cases ,please read the data until end of file. For each case: The first line contains a single integer n (1≤n?≤2*10^5) — 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

For each case 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

5

1 2 3 4 5

1 5 2 3 4

5

1 5 2 3 4

1 2 3 4 5

 

Sample Output

2

1

3

 

 

这是一道很有意思的题~

想到了方法的话就很简单啦

每次都只能将最后一个元素向前挪,求最小的挪动次数,使第一种情况转化为第二种情况

因为每次都只能挪动最后一个元素,所以如果在中间任意位置时,有第一种情况中的元素的位置在第二种情况中不相等,那么就一定要到不相等的位置处来挪动这个元素,使之相等。

所以,从一种情况的第一个元素开始遍历,找到其中的元素位置与第二种情况不相等时,就可以得出最小的挪动次数了。。。

 

代码实现:

View Code
 1 #include<iostream>
 2 using namespace std;
 3 struct node{
 4        int v;
 5        int p;
 6 };
 7 node first[200010];
 8 node second[200010];
 9 int main(){
10     int n;
11     while(cin>>n){
12         for(int i=0;i<n;i++){
13                 cin>>first[i].v;
14                 }
15         for(int j=0;j<n;j++){
16                 cin>>second[j].v;
17                 second[second[j].v].p=j;
18                 }
19         int k;
20         for(k=0;k<n-1;k++){
21                 if(second[first[k].v].p>second[first[k+1].v].p)
22                        break;
23                        }
24         cout<<n-1-k<<endl;
25         }
26     return 0;
27 }

 

posted on 2012-12-15 23:06  yumao  阅读(205)  评论(0编辑  收藏  举报

导航