(交换任意位置的两个元素使数组递增)CSL 的魔法

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

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

题目描述

有两个长度为 n 的序列,a0,a1,…,an−1a0,a1,…,an−1和 b0,b1,…,bn−1b0,b1,…,bn−1。CSL 有一种魔法,每执行一次魔法,可以任意挑选一个序列并任意交换序列中两个元素的位置。CSL 使用若干次魔法,得到最终的序列 a 和 b,并且想要让 a0b0+a1b1+…+an−1bn−1a0b0+a1b1+…+an−1bn−1的值最小化。求解 CSL 至少使用多少次魔法,能够达到最小化的目标。

输入描述:

第一行有一个整数 n,表示序列的长度。

接下来两行,每行有 n 个整数,分别表示初始序列 a 和 b。

输入数据保证每个序列里的数两两不同。

2≤n≤1052≤n≤105
1≤ai,bi≤1091≤ai,bi≤109

输出描述:

在一行输出一个整数,表示最少使用的魔法次数。

示例1

输入

复制

2
1 2
1 2

输出

复制

1

示例2

输入

复制

2
1 2
2 1

输出

复制

0
#include<set>
#include<map>
#include<list>
#include<queue>
#include<stack>
#include<math.h>
#include<vector>
#include<bitset>
#include<iomanip>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<unordered_map>
#define eps (1e-8)
#define MAX 0x3f3f3f3f
#define u_max 1844674407370955161
#define l_max 9223372036854775807
#define i_max 2147483647
#define re register
#define pushup() tree[rt]=tree[rt<<1]+tree[rt<<1|1]
#define nth(k,n) nth_element(a,a+k,a+n);  // 将 第K大的放在k位
#define ko() for(int i=2;i<=n;i++) s=(s+k)%i // 约瑟夫
#define ok() v.erase(unique(v.begin(),v.end()),v.end()) // 排序,离散化
#define Catalan C(2n,n)-C(2n,n-1)  (1,2,5,14,42,132,429...) // 卡特兰数
using namespace std;

inline int read(){
    char c = getchar(); int x = 0, f = 1;
    while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
    while(c >= '0' & c <= '9') x = x * 10 + c - '0', c = getchar();
    return x * f;
}

typedef long long ll;
const double pi = atan(1.)*4.;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3fLL;
const int M=63;
const int N=1e5+5;

int getMin(vector<int> &nums) {
    vector<int> nums1(nums);
    sort(nums1.begin(), nums1.end());
    unordered_map<int, int> m;
    int len = nums.size();
    for (int i = 0; i < len; i++) {
        m[nums1[i]] = i;
    }
    int loops = 0;
    vector<bool> flag(len, false);
    for (int i = 0; i < len; i++) {
        if (!flag[i]) {
            int j = i;
            while (!flag[j]) {
                flag[j] = true;
                j = m[nums[j]];
            }
            loops++;
        }
    }
    return len - loops;
}
struct fun{
    int x,y;
}f[N];

bool cmp(fun a,fun b){
    return a.x>b.x;
}
int main(){
    int n,x;
    scanf("%d",&n);
    int p=0;
    for(int i=1;i<=n;i++)
        scanf("%d",&f[i].x);
    for(int i=1;i<=n;i++)
        scanf("%d",&f[i].y);

    sort(f+1,f+n+1,cmp);
    vector<int>num;
    for(int i=1;i<=n;i++)
        num.push_back(f[i].y);
    printf("%d\n",getMin(num));
    return 0;
}

猜你喜欢

转载自blog.csdn.net/black_horse2018/article/details/88947216