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
Code:
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <vector> #include < Algorithm> #include <queue>using namespace std;vector<int>q[100001];//the BFS simulation of two-dimensional vector-based vectors traversing void bfs ( int n) {bool Vis[100001];memset (VIS, false, sizeof (VIS)); Queue<int>p;p.push (n); vis[n]=true; int Dd;vector<int>::iterator it; int Flag=0;int cnt[100001];memset (CNT, 0, sizeof), while (!p.empty ()) {Dd=p.front ();p. POPs (); for (It=q[dd].begin () ; It!=q[dd].end (); it++) {if (vis[*it]==false) {Cnt[*it]=cnt[dd]+1;p.push (*it); Vis[*it]=true;if (*it==1) {flag=1; break;}}} if (flag==1) break;} if (flag==0) printf ("no\n"); elseprintf ("%d\n", Cnt[1]);} int main () {int n, m;int u, v;int i, J;while (scanf ("%d%d", &n, &m)!=eof) {for (i=0; i<=100000; i++) {Q[i].clea R ();} for (i=0; i<m; i++) {scanf ("%d%d", &u, &v); Q[u].push_back (v); Q[v].push_back (u);} BFS (n);} return 0;} /**************************************problem Id:sdut OJ 2830 Result:accePted take memory:8312k take time:460ms Submit time:2015-01-18 09:39:14 **************************************/
Sdut OJ Chart Exercise-bfs-The shortest steps from the starting point to the target point (vector two-dimensional array simulation adjacency table +BFS, * "template")