#include <climits>
#include <iostream>
#include <set>
#include <vector>
using namespace std;
struct edge { int to, length; };
int dijkstra(const vector< vector<edge> > &graph, int source, int target) {
vector<int> min_distance( graph.size(), INT_MAX );
min_distance[ source ] = 0;
set< pair<int,int> > active_vertices;
active_vertices.insert( {0,source} );
while (!active_vertices.empty()) {
int where = active_vertices.begin()->second;
if (where == target) return min_distance[where];
active_vertices.erase( active_vertices.begin() );
for (const auto &ed : graph[where])
if (min_distance[ed.to] > min_distance[where] + ed.length) {
active_vertices.erase( { min_distance[ed.to], ed.to } );
min_distance[ed.to] = min_distance[where] + ed.length;
active_vertices.insert( { min_distance[ed.to], ed.to } );
}
}
return INT_MAX;
}
int main() {
vector< vector<edge> > graph = { { {1,1}, {3,2} }, { {2,1} }, { {3,1} }, { } };
cout << dijkstra(graph,0,3) << endl;
cout << dijkstra(graph,0,2) << endl;
cout << dijkstra(graph,1,2) << endl;
cout << dijkstra(graph,2,0) << endl;
}
I2luY2x1ZGUgPGNsaW1pdHM+CiNpbmNsdWRlIDxpb3N0cmVhbT4KI2luY2x1ZGUgPHNldD4KI2luY2x1ZGUgPHZlY3Rvcj4KdXNpbmcgbmFtZXNwYWNlIHN0ZDsKCnN0cnVjdCBlZGdlIHsgaW50IHRvLCBsZW5ndGg7IH07CgppbnQgZGlqa3N0cmEoY29uc3QgdmVjdG9yPCB2ZWN0b3I8ZWRnZT4gPiAmZ3JhcGgsIGludCBzb3VyY2UsIGludCB0YXJnZXQpIHsKICAgIHZlY3RvcjxpbnQ+IG1pbl9kaXN0YW5jZSggZ3JhcGguc2l6ZSgpLCBJTlRfTUFYICk7CiAgICBtaW5fZGlzdGFuY2VbIHNvdXJjZSBdID0gMDsKICAgIHNldDwgcGFpcjxpbnQsaW50PiA+IGFjdGl2ZV92ZXJ0aWNlczsKICAgIGFjdGl2ZV92ZXJ0aWNlcy5pbnNlcnQoIHswLHNvdXJjZX0gKTsKICAgIHdoaWxlICghYWN0aXZlX3ZlcnRpY2VzLmVtcHR5K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