wa #7 #8
查看原帖
wa #7 #8
965233
_Oxygen_楼主2023/8/22 18:19
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
using ll = long long;

typedef pair<int, int> PII;
const int N = 700010;
const ll inf = 0x3f3f3f3f3f3f3f3f;

ll h[N], e[N], ne[N], idx;
ll w[N]; 
ll dist[N];
bool st[N]; 
ll n, m;

void add(ll a, ll b, ll c){
    w[idx] = c;
    e[idx] = b;
    ne[idx] = h[a];
    h[a] = idx ++;
}

void dijkstra(){
    memset(dist, 0x3f, sizeof(dist));
    dist[1] = 0;
    priority_queue<PII, vector<PII>, greater<PII>> heap;
    heap.push({0, 1});
    while (heap.size()){
        auto t = heap.top();
        heap.pop();
        
        ll ver = t.second, dis = t.first;
        
        if (st[ver]) continue;
        st[ver] = true;
        
        for (int i = h[ver]; i != -1; i = ne[i]){
            auto j = e[i];
            if (dist[j] > dis + w[i]){
                dist[j] = dis + w[i];
                heap.push({dist[j], j});
            }
        }
    }
    
}

int main()
{
    memset(h, -1, sizeof h);
    cin >> n >> m;
    while (m -- ){
        int x, y, c;
        cin >> x >> y >> c;
        add(x, y, c);
    }
    
    dijkstra();
    
    for (int i = 1; i <= n; i ++)
    	if (dist[i] >= inf) cout << -1 << " ";
    	else cout << dist[i] << " ";

	return 0;
}
2023/8/22 18:19
加载中...