Redaksiya
Сonstruct a graph by assigning a weight of to the existing edges and a weight of to their reversed edges. Then, run a breadth-first search. The length of the shortest path from vertex to vertex will equal the minimum number of edges that need to be reversed.
Example
The graph in the example looks as follows:
Algorithm realization
Declare the constant infinity.
#define INF 0x3F3F3F3F
Declare the array of shortest distances and the adjacency list of the graph . For each edge, store its weight ( or ) along with the adjacent vertex.
vector<int> dist; vector<vector<pair<int, int> > > g;
The bfs function implements breadth-first search from the vertex .
void bfs(int start) { dist = vector<int>(n + 1, INF); dist[start] = 0; deque<int> q; q.push_back(start); while (!q.empty()) { int v = q.front(); q.pop_front(); for (auto edge : g[v]) { int to = edge.first; int w = edge.second; if (dist[to] > dist[v] + w) { dist[to] = dist[v] + w;
Depending on the weight of the edge , add vertex to the end or the front of the queue.
if (w == 1) q.push_back(to); else q.push_front(to); } } } }
The main part of the program. Read the input data.
scanf("%d %d", &n, &m); g.resize(n + 1); for (i = 0; i < m; i++) { scanf("%d %d", &a, &b);
Assign a weight of to a directed edge , and a weight of to the reverse edge.
g[a].push_back({ b, 0 }); g[b].push_back({ a, 1 }); }
Start the breadth-first search from the vertex .
bfs(1);
Print the answer — the shortest distance to vertex .
if (dist[n] == INF) printf("-1\n"); else printf("%d\n", dist[n]);