题解:P15291 [MCO 2023] Love Letter

· · 题解

link

Solution

一个方法就是每条龙之间都连一条边,跑最短路,但连边的时间复杂度和空间复杂度均为 O(n^2),会爆空间,超时。

但我们可以简化一下,把龙按年龄从小到大排序,相邻的龙和亲密的龙连边,可以证明能其他边能被替代。

:::info[证明] 假设排序后的数组为 b。

第 i 小的龙把信寄给第 j 小的龙(1 \le i < j \le n,j-i > 1,两条龙不是亲密好友)的时间是 b_j - b_i。

如果第 i 小的龙寄给 i+1,从 i+1 寄给 i+2,一直寄给 j,如果没有亲密好友之间的寄信,所需时间是 b_j - b_{j - 1} + b_{j - 1} - \dots - b_i = b_j - b_i,和原来相同,如果有,时间还会更短。

综上,其他边可以被替代。

Code

:::success[code]

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef char ch;
typedef string str;
const ll maxn=2e5+1,maxm=4e5+1;
struct edge
{
    ll v,w,nxt;
}e[maxm*2];
ll head[maxn],cnt,n,k;
struct node
{
    ll a,num;
    bool operator<(node nd) const
    {
        return a<nd.a;
    }
}a[maxn];
map<pair<ll,ll>,bool> mp;
void add(ll u,ll v,ll w)
{
    e[++cnt]={v,w,head[u]};
    head[u]=cnt;
}
struct Edge
{
    ll w,to;
    bool operator<(Edge ed) const
    {
        return w>ed.w;
    }
};
priority_queue<Edge> pq;
ll dis[maxn];
bool vis[maxn];
void init()
{
    memset(dis,0x3f,sizeof(dis));
    memset(vis,0,sizeof(vis));
    dis[1]=0;
}
void dijkstra()
{
    init();
    pq.push({0,1});
    while(pq.size())
    {
        Edge tp=pq.top();
        pq.pop();
        if(vis[tp.to]) continue;
        vis[tp.to]=1;
        for(int i=head[tp.to];i;i=e[i].nxt)
        {
            if(dis[e[i].v]>dis[tp.to]+e[i].w)
            {
                dis[e[i].v]=dis[tp.to]+e[i].w;
                pq.push({dis[e[i].v],e[i].v});
            }
        }
    }
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin>>n>>k;
    for(int i=1;i<=n;i++) cin>>a[i].a,a[i].num=i;
    sort(a+1,a+n+1);
    for(int i=1;i<=k;i++)
    {
        ll u,v;
        cin>>u>>v;
        mp[{u,v}]=mp[{v,u}]=1;
        add(u,v,0);
        add(v,u,0);
    }
    for(int i=1;i<n;i++)
    {
        if(mp.find({a[i].num,a[i+1].num})!=mp.end()) continue;
        add(a[i].num,a[i+1].num,a[i+1].a-a[i].a);
        add(a[i+1].num,a[i].num,a[i+1].a-a[i].a);
    }
    dijkstra();
    for(int i=1;i<=n;i++) cout<<dis[i]<<" ";
}

:::