You are on page 1of 2

#include <list>

#include <queue>
#include <vector>
#include <iostream>
#include <algorithm>
#include <utility>
#include <climits>

using namespace std;

class Comp {
public:
bool operator() (const pair<int, int> &lsh, const pair<int, int> &rsh) {
return lsh.second > rsh.second;
}
};

vector<int> dijkstra(const vector<list<pair<int, int>>> &graph, int start) {


vector<int> dist(graph.size(), INT_MAX);
vector<bool> visited(graph.size(), false);

dist[start] = 0;

priority_queue<pair<int, int>, vector<pair<int, int>>, Comp> pq;


pq.push(make_pair(start, 0));
while (!pq.empty()) {
pair<int, int> curr_node = pq.top();
pq.pop();

if (visited[curr_node.first])
continue;

visited[curr_node.first] = true;

for (list<pair<int, int>>::const_iterator it =


graph[curr_node.first].begin(); it != graph[curr_node.first].end(); ++it) {
if (!visited[it->first] && dist[it->first] > dist[curr_node.first] +
it->second) {
dist[it->first] = dist[curr_node.first] + it->second;
pq.push(make_pair(it->first, dist[it->first]));
}
}
}

return dist;
}

int main() {
std::ios_base::sync_with_stdio(false);

int t; cin >> t;


for (int a0 = 0; a0 < t; a0++) {
int n, m; cin >> n >> m;
vector<list<pair<int, int>>> graph(n + 1, list<pair<int, int>>());
for (int a1 = 0; a1 < m; a1++) {
int x, y, r; cin >> x >> y >> r;
graph[x].push_back(make_pair(y, r));
graph[y].push_back(make_pair(x, r));
}
int s; cin >> s;

vector<int> dist = dijkstra(graph, s);


for (int i = 1; i < dist.size(); ++i) {
if (i == s)
continue;

if (dist[i] == INT_MAX)
cout << "-1 ";
else
cout << dist[i] << " ";
}
cout << "\n";
}
return 0;
}

You might also like