跳到正文

题解

题解:AT_abc181_e [ABC181E] Transformable Teacher

Wicked_约 4 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年3月10日
篇幅
约 4 分钟

版本

  1. v2当前
  2. v1

显而易见有一个 Θ(n×m)\Theta(n\times m) 的暴力做法,对于 nn 个学生排序,最后大的减次大的,再枚举老师的 mm 种形态取最小值就行。

但是我们发现对于每一个老师的形态我们没有必要重新去把学生都给遍历一遍,我们只需要先二分找到和老师身高差距最小的学生的下标记为 pp,接着我们考虑是 ap+1a_{p+1} 和老师匹配还是 ap−1a_{p-1} 和老师匹配就好了,那么原来和学生 ap+1a_{p+1} 或 ap−1a_{p-1} 配对的学生,也要向后移一位,这个我们直接用前缀和处理就行。最后时间复杂度 Θ(mlog⁡n)\Theta(m \log n)。

但是题目中有很多细节实现时需要注意。

Ac Code
C++
#include<bits/stdc++.h>
using namespace std;
#ifdef __linux__
#define gc getchar_unlocked
#define pc putchar_unlocked
#else
#define gc _getchar_nolock
#define pc _putchar_nolock
#endif
#define int long long
#define R register
#define rint register int
#define _ read<int>()
inline bool blank(const char x)
{
    return !(x^9)||!(x^13)||!(x^10)||!(x^32);
}
template<class T>inline T read()
{
    T r=0,f=1;R char c=gc();
    while(!isdigit(c))
    {
        if(c=='-')f=-1;
        c=gc();
    }
    while(isdigit(c))r=(r<<1)+(r<<3)+(c^48),c=gc();
    return f*r;
}
inline void out(int x)
{
    if(x<0)pc('-'),x=-x;
    if(x<10)pc(x+'0');
    else out(x/10),pc(x%10+'0');
}
inline void read(char &x)
{
    for(x=gc();blank(x)&&(x^-1);x=gc());
}
const int N=2e5+10;
int a[N],b[N],s[N],ss[N];
signed main()
{
    rint n=_,m=_;
    for(rint i=1;i<=n;i++) a[i]=_;
    sort(a+1,a+n+1);
    for(rint i=1;i<=n;i++)
    {
        if(i&1) s[i]=s[i-1]+a[i],ss[i]=ss[i-1];//奇数的前缀和
        else ss[i]=ss[i-1]+a[i],s[i]=s[i-1];//偶数的前缀和
    }
    for(rint i=1;i<=m;i++) b[i]=_;
    rint ans=1145141919810;
    for(rint i=1;i<=m;i++)
    {
        rint p=lower_bound(a+1,a+n+1,b[i])-a;
        if(p>n)p=n;
        rint tmp=0;
        if(p&1)//是奇数
        {
            tmp+=abs((ss[p-1]-s[p-1]));
            tmp+=abs(a[p]-b[i]);
            if(p<n) tmp+=abs((s[n]-s[p])-(ss[n]-ss[p]));
        }
        else//是偶数
        {
            tmp+=abs((ss[p-2]-s[p-2]));
            tmp+=abs(a[p-1]-b[i]);
            tmp+=abs((s[n]-s[p-1])-(ss[n]-ss[p-1]));
        }
        ans=min(ans,tmp);//取最小值
    }
    out(ans);
    return 0;
}
原文