Codeforces Round #743 (Div. 2)


B. Swaps

思路:

把a,b數組開成pair,first存值,second存下標,然后把兩個數組排序,由於在同一位置下,a數組永遠小於b數組,所以我們每到一個位置,就取一個min的dist(a[i]到開頭的距離),保證a[i]的位置盡量靠前,然后再取一個min的res,由於下標從1開始,所以res取最小的b.second + dist - 2

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <cmath>

using namespace std;

typedef pair<int, int>PII;
typedef long long LL;

const int N = 100010;

PII a[N], b[N];

int main()
{
    int T;
    cin >> T;
    while (T--)
    {
        int n;
        cin >> n;
        for (int i = 1; i <= n; i++) cin >> a[i].first, a[i].second = i;
        for (int i = 1; i <= n; i++) cin >> b[i].first, b[i].second = i;

        sort(a + 1, a + 1 + n);
        sort(b + 1, b + 1 + n);

        int dist = 0x3f3f3f3f, res = 0x3f3f3f3f;
        for (int i = 1; i <= n; i++)
        {
            dist = min(dist, a[i].second);//隨着i的增加,a[i]要保證位置要盡量靠前
            res = min(res, b[i].second + dist - 2);
        }

        cout << res << endl;
    }
    return 0;

}

//3(1) 1(2)
//4(1) 2(2)
//
//1(2) 3(1)
//2(2) 4(1)
//
//7(1) 5(2) 9(3) 1(4) 3(5)
//2(1) 4(2) 6(3) 10(4) 8(5)
//
//1(4) 3(5) 5(2) 7(1) 9(3)
//2(1) 4(2) 6(3) 8(5) 10(4)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM