$ Noip2013 / Luogu1966 $ matches discrete queuing greedy + + reverse order

$ Luogu $

 

$Description$

Given equal length $ a, b $ two sequences each time sequence may exchange a number of two adjacent minimum required number of exchanges that $ \ sum (a_i-b_i) ^ 2 $ minimized.

 

$Sol$

Swap meet certain sequence after sequence $ a $ large number of the first $ i $ and $ b $ in the sequence of the $ i $ large number corresponds to. Prove quite obviously did not say, Los ri explanations given some a pair then the number of discrete two sequences, the sequence of conversion $ b $ $ I $ of the large number of $ $ to position a $ I $ sequence where a large number. the question then transformed into , $ b $ exchange sequence how many times can turn into $ a $, and because the discrete $ a $ sequence is a single increase, in fact, $ 1,2,3 ....., n $. so this is only required when $ b $ sequence reverse to like you may be used to sort or merge tree array.

 

$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,v =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;
}
View Code

 

 

 

Guess you like

Origin www.cnblogs.com/forward777/p/11414336.html