zoukankan      html  css  js  c++  java
  • 图论--最短路径生成树(求最小边权和)

    #include<iostream>
    #include<cstring>
    #include<sstream>
    #include<cstdio>
    #include<algorithm>
    #include<queue>
    using namespace std;
    #define read(x) scanf("%lld",&x)
    #define Read(x,y) scanf("%lld%lld",&x,&y)
    #define gc(x)  scanf(" %c",&x)
    #define mmt(x,y)  memset(x,y,sizeof x)
    #define write(x) printf("%d
    ",x)
    #define INF 0x3f3f3f3f
    #define ll long long
    #define mod  ((1LL<<31) - 1LL)
    const  ll N = 3e5+5;
    const ll M = 1e6;
    ll d[N];
    bool vis[N];
    ll head[N],tot;
    ll p[N];
    struct Edge
    {
        ll next;
        ll to;
        ll dis;
    }edge[N*2];
    inline void add(ll from,ll to,ll dis)
    {
        edge[++tot].next = head[from];
        edge[tot].to = to;
        edge[tot].dis = dis;
        head[from] = tot;
    }
    struct node
    {
        ll id,val;
        node(){}
        node(ll a,ll b):id(a),val(b){}
        bool operator <(node A)const{
            return val > A.val;
        }
    };
    void dij(ll u)
    {
        mmt(p,0x7f);
        mmt(d,0x7f);
        mmt(vis,0);
        d[u] = 0;
        p[u] = 0;
        priority_queue<node> Q;
        Q.push({u,0});
        node tmp;
        while(Q.size()){
            tmp = Q.top();
            Q.pop();
            int x = tmp.id;
            if(vis[x]) continue;
            vis[x] = 1;
            for(int i = head[x];~i;i = edge[i].next){
                int  y = edge[i].to;
                ll dis = edge[i].dis;
                if(d[y] >= d[x] + dis){
                    p[y] = min(p[y],dis);
                    d[y] = d[x] +dis;
                    Q.push({y,d[y]});
                }
            }
        }
    }
    void init()
    {
        mmt(head,-1);
        tot = 0;
    }
    int main()
    {
        init();
        ll n,m;
        ll f,t,dis;
        Read(n,m);
        for(ll i = 1;i <= m;++i){
            Read(f,t);read(dis);
            add(f,t,dis);
            add(t,f,dis);
        }
        read(t);
        dij(t);
        ll ans = 0;
        for(int i = 1;i <= n;++i){
           ans += p[i];
        }
        cout<<ans<<endl;
    }
    
    
  • 相关阅读:
    [转载]C#.NET中Dns类的常用方法及说明
    [转载]如何辨别真假百度蜘蛛
    Lottie的json动画
    iOT
    iOS字体大小
    针对Xcode 9 + iOS11 的修改,及iPhone X的适配
    shell脚本之 给PNG图片添加后缀@3x
    正则表达式
    CSS
    XcodeProj,使用Ruby更改工程文件
  • 原文地址:https://www.cnblogs.com/lunatic-talent/p/12798651.html
Copyright © 2011-2022 走看看