【Henu ACM Round#16 E】Paths and Trees

【链接】 我是链接,点我呀:)
【题意】

在这里输入题意

【题解】

感觉很像一道最短路。 然后就试了一发。 结果真的是。。

只要用一个优先队列优化的dijkstra算法求出每个点的最短路上的前一个点是什么就可以了。
相同大小的话.取每个边的前一个边的边权较小的那个。

然后把每个点的前缀边输出就好。

【代码】

#include <bits/stdc++.h>
#define ll long long
using namespace std;

const int N = 3e5;

struct abc{
    int x,y,z;
}a[N+10];

int n,m,s,pre[N+10];
ll dis[N+10];
vector<int> g[N+10];
priority_queue <pair<ll,int>,vector<pair<ll,int> >,greater<pair<ll,int> > > pq;

int main(){
	#ifdef LOCAL_DEFINE
	    freopen("rush_in.txt", "r", stdin);
	#endif
	ios::sync_with_stdio(0),cin.tie(0);
    cin >> n >> m;
    for (int i = 1;i <= m;i++){
        cin >> a[i].x >> a[i].y >> a[i].z;
        g[a[i].y].push_back(i);
        g[a[i].x].push_back(i);
    }
    cin >> s;
    memset(dis,255,sizeof dis);
    dis[s] = 0;
    pq.push({dis[s],s});
    while (!pq.empty()){
        pair<ll,int> temp = pq.top();
        pq.pop();
        ll disx = temp.first;int x = temp.second;
        if (dis[x]!=disx) continue;
        for (int index:g[x]){
            int y = x^a[index].x^a[index].y;ll cost = a[index].z;
            if (dis[y]==-1 || dis[y]>dis[x]+cost){
                pre[y] = index;
                dis[y] = dis[x]+cost;
                pq.push({dis[y],y});
            }else if (dis[y]==dis[x]+cost && a[pre[y]].z>a[index].z){
                pre[y] = index;
                pq.push({dis[y],y});
            }
        }
    }
    ll ans1 = 0;
    for (int i = 1;i <= n;i++)
        if (i!=s){
            int now = pre[i];
            ans1+=a[now].z;
        }
    cout<<ans1<<endl;
    for (int i = 1;i <= n;i++)
        if (i!=s)
            cout<<pre[i]<<' ' ;

	return 0;
}
原文地址:https://www.cnblogs.com/AWCXV/p/8433031.html