Figure exercise-bfs-the shortest number of steps from the start to the target point Time limit:1000ms Memory limit:65536k have questions? Dot here ^_^ Title description in the ancient Warcraft legend, there are two legions, one called the Scourge, one called Janissary. In their area, there are n passes, numbered 1. N, there is a channel connection between some passes. Among them, the Legion was in the 1th, and the Scourge was in the N. One day, the leader of the Scourge, the Lich King, decided to send troops to attack the Guards Regiment, which is so large that the scourge can even fill the river. But the Lich King did not want to pay an unnecessary price, and he wondered whether, without the construction of any passages, the troops could reach the Guards regiment through the pass and its associated passages, and if so, how many channels would be required at least. Since the value of n is larger (n<=100000), the Lich King has found you =_= good at programming, ask you to help him solve this problem, or you will eat into his magic. To save yourself, find a way. The input input contains multiple groups, each set in the following format. The first line contains two integers n (n <= 100000), M (M <= 200000) (representing n passes, each of which has m channels). The following M-line contains two integers per line, a, a, or a, which indicates a passage from A to B pass (note: The channel is bidirectional). Output if the scourge can reach the No. 1th pass without building any channels, the output will be at least as many channels as the output No. Sample input
2 11 22) 12 1
Sample output
11
Hint Source ZMX sample program
#include <iostream> #include <algorithm> #include <stdio.h> #include <string.h> #include < stdlib.h> #include <queue> #include <vector>using namespace std;const int maxn = 100001;struct node{int x; int ans;}; int N,m;vector<int>p[maxn];int v[maxn];int flag;void BFS () {memset (v,0,sizeof (v)); Queue<struct node>q; while (!q.empty ()) {Q.pop (); } struct node t,f; T.x = n; T.ans = 0; Q.push (t); V[t.x] = 1; while (!q.empty ()) {t = Q.front (); Q.pop (); for (int i=0;i<p[t.x].size (); i++) {if (v[p[t.x][i]] = = 0) {f.x = P[t.x][i]; F.ans = T.ans + 1; if (p[t.x][i] = = 1) {flag = F.ans; return; } q.push (f); V[p[t.x][i]] = 1; }}}}int Main () {while (scanf ("%d%d", &n,&m)!=eof) {FLAg = 0; for (int i=0;i<=n;i++) {p[i].clear (); } int x, y; for (int i=0;i<m;i++) {scanf ("%d%d", &x,&y); P[x].push_back (y); P[y].push_back (x); } BFS (); if (flag) {printf ("%d\n", flag); } else {printf ("no\n"); }} return 0;}
Sdut 2830 Figure Exercise-bfs-The shortest steps from the starting point to the target point (BFS + vector)