图论--最短路径生成树(求最小边权和)

#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\n",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;
}

 

posted @ 2019-10-27 17:32  风骨散人  阅读(129)  评论(0编辑  收藏  举报