牛客网——第十八届浙大城市学院程序设计竞赛(同步赛)G题Permutation

链接:https://ac.nowcoder.com/acm/contest/12986/G
来源:牛客网

时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 524288K,其他语言1048576K
64bit IO Format: %lld

G题Permutation

题目描述

You are given two permutations a and b of length n.
A permutation is a sequence of length n integers from 1 to n , in which all the numbers occur exactly once. For example, [1], [1,3,2], [3,1,5,2,4]
are permutations, and [2], [1,1] are not.
There are two types of operations as follow:
1.Remove the first integer in a . Then append any integer at the end of a .
2.Choose an ai​ (1≤i≤n) and modify it to any integer.
You have to find the minimum number of operations to make a and b
the same.
Be attention, you do not have to keep a in a permutation during the process.

输入描述:

The first line contains an integer n(1≤n≤10^6 ) — the length of a
and b .
The second line contains n integers a 1,a 2​ ,…,a n (1≤a i ≤n) .The third line contains n integers b 1,b 2​ ,…,b n (1≤b i ≤n) .
It is guaranteed that a and b are both permutations.

输出描述:

Output the minimum number of operations to make a and b the same.

示例1

输入

5
5 2 3 4 1
5 3 2 1 4

输出

3

说明

For the first example, there is a possible way:

  1. Remove the first integer in a and append 4, now a becomes [2,3,4,1,4].
  2. modify a 1​ to 5, now a becomes [5,3,4,1,4] .
  3. modify a 3 to 2 , now a becomes [5,3,2,1,4]
    So it only takes 3 operations to convert a into b .

思路:内容就是以最少次数将数组a->数组b。从文中可以看出有两种修改方式,一是将数组向前移动一格,并在尾部任意添加一个数字;二是任意修改数组中的一个数字。可以看出移动的效率值一定>=1,而修改只能是1。而且题目中明确指出数组中的数字是单一的,我们就可以利用下标位置找出移动效率最高的也就是次数最多的那个。
最终次数=需要移动步数+(总长度-需要移动步数-效率最高次数)<=>次数=总长度-效率最高次数
个人感觉有点贪心的思想。

正确代码:

#include<iostream>
#include<stdio.h>
#include<math.h>
#include<algorithm>
using namespace std;
long long a[1000005];
long long b[1000005];
int main(){
	ios::sync_with_stdio(false);
	int x,n;
	
	while(cin>>n){
		long long  maxn=0;
		b[0]=0;
		for(int i=1;i<=n;i++){
			cin>>x;
			a[x]=i;
			b[i]=0;
		}
		for(int i=1;i<=n;i++){
			cin>>x;
			if(a[x]-i>=0){
				b[a[x]-i]++;
				maxn=max(b[a[x]-i],maxn);
			}
		}
		cout<<n-maxn<<endl;
	} 
	return 0;
} 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值