Codeforces Round #743B Swaps(思维)

cf变成oi赛制了
想要让a数组比b数组小,其实只需要让a数组第一位比b数组小
由题目数据特性可知,如果对a,b两数组按值大小进行排序,那么在同一下标下,a数组必定是小于b数组的
所以只需要开一个结构体,储该点的值和原本位置。然后按值的大小sort一遍,然后找出下标最靠前的那一对就好

#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 1e5 + 10;

int n;
struct node {
    
    
	int val, idx;//值 位置
} a[N], b[N];

bool cmp(node i, node j) {
    
    
	return i.val < j.val;
}

void solve() {
    
    
	cin >> n;
	for (int i = 1; i <= n; i++) {
    
    
		cin >> a[i].val;
		a[i].idx = i;
	}
	for (int i = 1; i <= n; i++) {
    
    
		cin >> b[i].val;
		b[i].idx = i;
	}
	int ans = 1e8;
	int res = 1e8;
	sort(a + 1, a + 1 + n, cmp);
	sort(b + 1, b + 1 + n, cmp);
	for (int i = 1; i <= n; i++) {
    
    
		ans = min(ans, a[i].idx);//随着i的增加,ans要保证位置要尽量靠前
		//因为数据的特性保证了在同一位置上a永远小于b
		res = min(res, b[i].idx + ans - 2);
	}
	cout << res << endl;


}

signed main() {
    
    
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	int t;
	cin >> t;
	while (t--) {
    
    
		solve();
	}
}

おすすめ

転載: blog.csdn.net/fdxgcw/article/details/120377741