[SCOI2008] pairing problem solving report

[SCOI2008] pairing

The meaning of problems

There \ (n-\) integers \ (a_i, B_i \) ( \ (a_i \) varies, \ (B_i \) is also different),
\ ((. 1 \ Le n-\ Le 10 ^. 5, \ . 1 \ Le a_i, B_i \ Le ^ 10. 6) \) , the \ (a_i, b_j \) paired off, require the same number of two pairing such that each sum of absolute values of difference between the minimum number, the output of this minimum.

Thinking

First, \ (a, b \) from small to large, Ruoguo not "the same two numbers can not be matched," this condition, then put each pair \ (a_i, b_i \) pair must be optimal.

Since \ (a, b \) numbers vary, so for an equal \ (a_i, \ B_i \) , the number of groups may be 3 or less digested it,
if it be paired with a number of further, certainly not optimal,

So, we can enumerate three groups \ (a_i, b_i \) all the way paired off, and then take the minimum on the line.

Code

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N=1e5+7;
const ll inf=1e17;
int n;
ll a[N],b[N],f[N];
int main(){
//  freopen("match.in","r",stdin);
    cin>>n; for(int i=1;i<=n;i++) scanf("%lld%lld",&a[i],&b[i]);
    sort(a+1,a+1+n); sort(b+1,b+1+n);
    if(a[1]==b[1]) f[1]=inf;
    else f[1]=abs(a[1]-b[1]);
    if(a[1]==b[1]||a[2]==b[2]) f[2]=abs(a[2]-b[1])+abs(a[1]-b[2]);
    else f[2]=abs(a[2]-b[2])+abs(a[1]-b[1]);
    for(int i=3;i<=n;i++){
        ll t1=inf,t2=inf,t3=inf,t4=inf,t5=inf;;
        if(a[i]!=b[i]) t1=f[i-1]+abs(a[i]-b[i]);
        if(a[i]!=b[i-1]){
            if(a[i-1]!=b[i]) t2=f[i-2]+abs(a[i]-b[i-1])+abs(a[i-1]-b[i]);
            if(a[i-1]!=b[i-2]&&a[i-2]!=b[i]) t3=f[i-3]+abs(a[i]-b[i-1])+abs(a[i-1]-b[i-2])+abs(a[i-2]-b[i]);
        }
        if(a[i]!=b[i-2]){
            if(a[i-1]!=b[i]&&a[i-2]!=b[i-1]) t4=f[i-3]+abs(a[i]-b[i-2])+abs(a[i-1]-b[i])+abs(a[i-2]-b[i-1]);
            if(a[i-1]!=b[i-1]&&a[i-2]!=b[i]) t5=f[i-3]+abs(a[i]-b[i-2])+abs(a[i-1]-b[i-1])+abs(a[i-2]-b[i]);
        }
        f[i]=min(min(t1,min(t2,t3)),min(t4,t5));
    }
    printf("%lld\n",f[n]);
    return 0;
}

Guess you like

Origin www.cnblogs.com/brucew-07/p/11807482.html