跳到正文

题解

题解:P15291 [MCO 2023] Love Letter

NoneOfTheAbove约 4 分钟
原文

这是 2026年2月19日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2026年2月19日
收录
2026年2月19日
更新
2026年11月14日
篇幅
约 4 分钟
获赞
1
题目
P15291

版本

  1. v2当前
  2. v1

link

Solution

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

但我们可以简化一下,把龙按年龄从小到大排序,相邻的龙和亲密的龙连边,可以证明该方法是最优的。

Code

code
C++
#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]<<" ";
}