Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <limits>
- #include <queue>
- #include <algorithm>
- using namespace std;
- typedef pair<int, int> parint;
- typedef vector< vector<parint> > graph;
- const int infinit = numeric_limits<int>::max();
- void dijkstra(const graph& g, int u, vector<int>& d, vector<int>& p) {
- int n = g.size();
- vector<bool> visto(n, false);
- d[u] = 0;
- p[u] = 0;
- queue<parint> q;
- q.push(parint(u,0));
- while(not q.empty()) {
- int v = (q.front()).first;
- q.pop();
- if(not visto[v]) {
- visto[v] = true;
- for(int i = 0; i < (int)g[v].size(); ++i) {
- int w = g[v][i].first; //vertice adj
- int r = g[v][i].second;
- //if(not visto[w]) {
- if(d[w] > d[v] + r) {
- d[w] = d[v] + r;
- p[w] = v;
- q.push(parint(w,d[w]));
- }
- //}
- }
- }
- }
- }
- void escribir(const vector<int>& c, int v0, int vf) {
- if(v0 != vf) {
- escribir(c,v0,c[vf]);
- cout << c[vf] << " ";
- }
- }
- bool comp(const parint& a, const parint& b) {
- return a.first < b.first;
- }
- int main() {
- int n, m;
- while(cin >> n >> m) {
- graph g(n);
- for(int i = 0; i < m; ++i) {
- int u, v;
- cin >> u >> v;
- g[u].push_back(parint(v,1));
- }
- //ordenem les adjacencies abans de fer el dijkstra
- for(int i = 0; i < n; ++i) {
- sort(g[i].begin(), g[i].end(), comp);
- }
- vector<int> dist(n, infinit);
- vector<int> path(n, -1);
- dijkstra(g, 0, dist, path);
- //0 el vertex inicial
- //a path tindre el cami mes curt
- escribir(path, 0, n-1);
- cout << n-1 << endl;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement