$Luogu$

$Description$

给定等长的$a,b$两个序列.每次可以交换一个序列中相邻两个数.求最小的交换次数使得$\sum(a_i-b_i)^2$最小.

$Sol$

交换后的序列一定满足$a$序列中第$i$大的数和$b$序列中第$i$大的数对应.证明挺显然的就不说了,洛谷里的题解一定有的叭.然后把两个序列中的数离散化,把$b$序列中第$i$大的数转换成$a$序列中第$i$大的数所在的位置.于是问题就转化成了,$b$序列中交换多少次能变成$a$,又因为离散化后$a$序列是单增的,其实就是$1,2,3.....,n$.所以只要求此时$b$序列中的逆序对就好了.可以用归并排序或树状数组.

$Code$

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
#define il inline
#define Rg register
#define go(i,a,b) for(Rg int i=a;i<=b;++i)
#define yes(i,a,b) for(Rg int i=a;i>=b;--i)
#define mem(a,b) memset(a,b,sizeof(a))
#define ll long long
#define db double
#define inf 2147483647
using namespace std;
il int read()
{
Rg int x=0,y=1;char c=getchar();
while(c<'0'||c>'9'){if(c=='-')y=-1;c=getchar();}
while(c>='0'&&c<='9'){x=(x<<1)+(x<<3)+c-'0';c=getchar();}
return x*y;
}
const int N=100010,mod=99999997;
int n,c[N],d[N],e[N];
ll as;
struct node{int w,pos,dx;}a[N],b[N];
il bool cmp1(node x,node y){return x.w<y.w;}
il bool cmp2(node x,node y){return x.pos<y.pos;}
il void lsh()
{
sort(a+1,a+n+1,cmp1);
sort(b+1,b+n+1,cmp1);
go(i,1,n)c[i]=a[i].pos;
go(i,1,n)b[i].dx=i;
sort(b+1,b+n+1,cmp2);
go(i,1,n)d[i]=c[b[i].dx];
}
il void gb(int l,int r)
{
if(l==r)return;
Rg int mid=(l+r)>>1,i=l,j=mid+1;
gb(l,mid);gb(mid+1,r);
go(k,l,r)
{
if((d[i]>d[j]&&j<=r)||i>mid)as=(as+(mid-i+1))%mod,e[k]=d[j++];
else e[k]=d[i++];
}
go(k,l,r)d[k]=e[k];
}
int main()
{
n=read();
go(i,1,n)a[i].w=read(),a[i].pos=i;
go(i,1,n)b[i].w=read(),b[i].pos=i;
lsh();
gb(1,n);
printf("%lld\n",as);
return 0;
}

随机推荐

  1. AspNetPager 样式

    使用方法: 1.引入样式表. 将 想要使用的样式表加入到本页面<style type="text/css"></style>标记中,或者新建一个css文件如 ...

  2. This cache store does not support tagging.

    用户权限管理系统 https://github.com/Zizaco/entrust 再添加角色的时候... 报了一个错.. BadMethodCallException in Repository. ...

  3. oracle函数 NLS_LOWER(x[,y])

    [功能]返回字符串并将字符串的变为小写; [参数]x字符型表达式 [参数]Nls_param可选,指定排序的方式(nls_sort=) . SCHINESE_RADICAL_M(部首.笔画) SCHI ...

  4. loadrunner_关联检查点参数化

    1.保存变量函数 lr_save_string("192.168.xx.xx","ip"); URL=http://{ip} 2.检查点函数 web_reg_f ...

  5. Getting started with the basics of programming exercises_1

    1.编写一个将输入复制到输出的程序,并将其中连续的多个空格用一个空格代替 使用if 结构: #include<stdio.h> #define NONBLANK 'a'; // repal ...

  6. 2019-1-29-C#-Task.Run-和-Task.Factory.StartNew-区别

    title author date CreateTime categories C# Task.Run 和 Task.Factory.StartNew 区别 lindexi 2019-01-29 16 ...

  7. Ralasafe

    引用:http://www.baike.com/wiki/Ralasafe Ralasafe 是用Java编写的开源(MIT协议)访问控制中间件.它能够轻松处理登录控制.URL权限控制和(业务级)数据 ...

  8. 【codeforces 766B】Mahmoud and a Triangle

    time limit per test2 seconds memory limit per test256 megabytes inputstandard input outputstandard o ...

  9. html设置<input type="text">内的内容自动为大写

    添加css样式:text-transform:uppercase;可以实现自动转换为大写样式. 但是input 的value还是小写的,因为它是CSS样式. <input type=" ...

  10. 【t090】吉祥数

    Time Limit: 1 second Memory Limit: 128 MB [问题描述] 为了迎接圣诞,信息学兴趣小组的同学在辅导老师的带领下,举办了一个盛大的晚会,晚会的第一项内容是做游戏: ...