51nod 1574 排列转换 codeforce584E. Anton and Ira

探讨了将乱序排列转换为有序排列的算法,通过计算交换两个数下标的绝对值作为代价,寻找最优解。文章详细介绍了算法实现过程,包括使用C++编程语言和数据结构如map和vector。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文章目录

题目链接:

51nod 1574
cf584E

先转换一哈题意,就是乱序的排列,把他变成有序的,交换两个数的代价是两个数下标的绝对值,问最小的代价

我就按顺序来,从小到大依次把每个数换到他该在的地方
一开始以为只要是对序列有贡献应该就阔以,代价应该是不变的,只要不是换过去又换回来那种浪费就行
但是2 3 1这个例子就让我否定了这个猜想,先把1换到对应位置需要2的代价,然后再换又需要1的代价,但是实际上这个总共只需要2的代价。
哪里计算多了喃?
就是2这个数,与1换的时候换到3的位置了,跑到他本来该在的位置的右边了,之后又要换回左边去,就在这里就浪费了,因此,我们只需要找到两个都往他该在的位置靠的两个数就行了,有了这个思路自己慢慢调就行了~

#include"bits/stdc++.h"
using namespace std;
typedef long long LL;
const int maxn=2e5+5;
const int MOD=1e9+7;
pair<int,int>pir[maxn];
int a[maxn];
map<int,int>Mp;
int main()
{
	int N;
	while(cin>>N)
	{
		Mp.clear();
		for(int i=1; i<=N; i++)
		{
			int t;
			scanf("%d",&t);
			Mp[t]=i;
		}
		for(int i=1; i<=N; i++)
		{
			int t;
			scanf("%d",&t);
			a[i]=Mp[t];
		}
		for(int i=1; i<=N; i++)Mp[a[i]]=i;//记录a[i]这个数的位置 
		LL ans=0;
		for(int i=1; i<=N; i++)
		{
			while(a[i]!=i)
			{
				int pos=Mp[i];
				int t=i;
				while(a[t]<pos)t++;
				ans+=abs(pos-t);
				swap(a[pos],a[t]);
				Mp[a[pos]]=pos;
				Mp[a[t]]=t;
			}
		}
		cout<<ans<<endl;
	}
}

cf584E

#include"bits/stdc++.h"
using namespace std;
typedef long long LL;
const int maxn=2e6+5;
const int MOD=1e9+7;
vector<pair<int,int> >pir;
int a[maxn];
map<int,int>Mp;
int main()
{
	int N;
	while(cin>>N)
	{
		Mp.clear();
		pir.clear();
		for(int i=1; i<=N; i++)
		{
			int t;
			scanf("%d",&t);
			Mp[t]=i;
		}
		for(int i=1; i<=N; i++)
		{
			int t;
			scanf("%d",&t);
			a[i]=Mp[t];
		}
		for(int i=1; i<=N; i++)
		{
			Mp[a[i]]=i;
		}
		LL ans=0;
		for(int i=1; i<=N; i++)
		{
			while(a[i]!=i)
			{
				int pos=Mp[i];
				int t=i;
				while(a[t]<pos)t++;
				ans+=abs(pos-t);
				swap(a[pos],a[t]);
				Mp[a[pos]]=pos;
				Mp[a[t]]=t;
				if(t>pos)swap(t,pos); 
				pir.push_back(make_pair(t,pos));
			}
		}
		cout<<ans<<endl;
		cout<<pir.size()<<endl;
		for(int i=pir.size()-1; i>=0;i--)cout<<pir[i].first<<" "<<pir[i].second<<endl;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值