题解:P10046 [CCPC 2023 北京市赛] 哈密顿

· · 题解

绝对值很烦。考虑将相邻两条边的绝对值拆出来,有以下四种:

然后你会发现,如果实际上能拼出来合法路径但拼不出来一个权值符合要求的图则一定中间会出现两个相减为负数,则一定不优。于是我们只需要使用上面四种使得能够拼出来一条合法路径即可。

注意到因为绝对值都是一正一负,所以首先正负号一定要相等,即第二种和第四种个数要相等。

而第一种和第三种分别可以单独出现。若要同时出现,则至少有一个第二种和第四种。

显然可以从一开始全都是第一种和第三种,然后不断加入第二种和第四种边取最大值。可以用优先队列简单维护。

注意到除了第一次替换以外别的每次替换若替换了两个相同的一定不优,则不需要处理相同的情况。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int NN=1e5+4;
struct node
{
    int a,b,w1,w2;
    bool operator<(const node&it)const
    {
        return w1<it.w1;
    }
}t[NN];
int main()
{
    int n;
    scanf("%d",&n);
    ll s1=0,s2=0;
    for(int i=1;i<=n;i++)
    {
        int a,b;
        scanf("%d%d",&a,&b);
        s1+=a-b,s2+=b-a;
        t[i]={a,b,a+b,abs(a-b)};
    }
    ll res=0;
    sort(t+1,t+1+n);
    priority_queue<pair<ll,int> >q1,q2;
    for(int i=1;i<=n;i++)
    {
        res+=t[i].w2;
        q1.push({t[i].w1-t[i].w2,i}),q2.push({-t[i].w1-t[i].w2,i});
    }
    ll ans=max(s1,s2);
    while(q1.size()&&q2.size())
    {
        if(q1.top().second!=q2.top().second)
            res+=q1.top().first+q2.top().first;
        else
        {
            int a=q1.top().first,b=q2.top().first;
            q1.pop(),q2.pop();
            if(!q1.size())
                break;
            res+=max(q1.top().first+b,a+q2.top().first);
        }
        q1.pop(),q2.pop();
        ans=max(ans,res);
    }
    printf("%lld",ans);
    return 0;
}