题解:P9327 [CCC 2023 S4] Minimum Cost Roads

· · 题解

既然题目要求任意两点间最短路最小的同时,价格也最小,那么我们就按长度为第一关键字,花费为第二关键字排序。然后遍历所有边看看这条边能否使用。

遍历过程的策略:

但是这样会超时。

考虑优化,发现对于遍历每条边的时候,我们只需要知道这条边两端节点的距离就行了,所以我们可以用 O(n\log m) 判断和 O(1) 更新的最短路算法代替 O(1) 判断和 O(n^2) 更新的暴力算法,再度优化,当两个节点没有任何路径相连时,这条边一定加入,这里我们可以通过判断是否位于一个集合处理。

所以最后的时间复杂度就应该是 O(\frac{2m+n\log m+\log n}{2}) 这样的一个数值。

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const ll maxs=2e18;
struct node
{
    ll x,y,l,c;
}e[2005];
bool cmp(node a,node b)
{
    if(a.l!=b.l)
      return a.l<b.l;
    return a.c<b.c;
}
ll fa[2005];
ll finds(ll now)
{
    return now==fa[now]?now:fa[now]=finds(fa[now]);
}
struct unit
{
    ll to,len;
};
vector<unit> G[2005];
struct fresh
{
    ll pos,val;
    bool operator<(const fresh&b) const
    {
        return b.val<val;
    }
};
ll n,m;
bool check(ll s,ll t,ll d)
{
    priority_queue<fresh> q;
    ll dis[2005];
    for(ll i=1;i<=n;i++) 
      dis[i]=maxs;
    q.push({s,0});
    while(q.size())
    {
        ll now=q.top().pos,val=q.top().val;
        q.pop();
        if(now==t)
          return d<val;
        if(dis[now]<=val) 
          continue;
        dis[now]=val;
        for(auto next:G[now])
        {
            ll to=next.to,len=next.len;
            if(dis[now]+len<dis[to])
              q.push({to,len+dis[now]});
        }
    }
    return true;
}
int main()
{
    cin>>n>>m;
    for(ll i=1;i<=n;i++) 
      fa[i]=i;
    for(ll i=1;i<=m;i++)
    {
        cin>>e[i].x>>e[i].y>>e[i].l>>e[i].c;
    }
    sort(e+1,e+1+m,cmp);
    ll cost=0;
    for(ll i=1;i<=m;i++)
    {
        ll x=e[i].x,y=e[i].y,l=e[i].l,c=e[i].c;
        if(finds(x)!=finds(y)||check(x,y,l))
        {
            cost+=c;
            G[x].push_back({y,l});
            G[y].push_back({x,l});
            fa[finds(x)]=finds(y);
        }
    }
    cout<<cost;
    return 0;
}