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
3 2 1
1 2 3
Output
2
Input
5
1 2 3 4 5
1 5 2 3 4
Output
1
Input
5
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]则说明这个数可以不用移动或者可以通过被其他数主动移动而被动的移动到自己该处在的位置,如果不想等,那么说明他所处的位置在自己应该处的位置的后边,那就必须前移。
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- Permutations
- SQL判断语句用法和多表查询
- CodeForces - 645C Enduring Exodus (二分)
- 关于逆地理编码的一些记录
- 练习003
- HashMap中的put(Object key, Object value)方法实现
- Permutations
- POJ 3037 Skiing(Dijkstra)
- 加锁
- php 获取客户端的ip、地理信息、浏览器信息、本地真实ip
- java线程模型 线程池
- SystemUI statusbar 更换自己的UI图标
- C
- 网易互娱2017实习生招聘游戏研发工程师在线笔试第二场(神奇的数)
- Android 读取网络数据