1. 程式人生 > >51nod 1574 排列轉換 codeforce584E. Anton and Ira

51nod 1574 排列轉換 codeforce584E. Anton and Ira

文章目錄

題目連結:

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;
	}
}