Simplified version of the shortest path

Reprint| Original link

Problem Description

After a busy week of work, Mr. Garantou wanted to take advantage of the weekend to have a good time. He wants to go to many, many places. He wants to go to Nanluoguxiang to eat all kinds of delicious food, to go ice skating in the Summer Palace, and to go skiing at Huairou Ski Resort... But time is limited, so he can't visit all the places, and finally He decided to go to a few closer to him.
We know that Mr. Tuantou wants to go to N places to play, numbered from 1 to N, and we know the number C of the place where Mr. Tuantou is, and the M paths. Now Mr. Tuantou wants you to help him calculate, how many places does he need to go through each place?
Input format Input three positive integers N, M, C in the
first line. It means that Mr. Tuantou wants to go to N places, there are M paths, and Mr. Tuantou is at the place numbered C. 1≤N, C≤1000, 1≤C≤N, 1≤M≤10000.
It is guaranteed that there are no duplicate edges and that all points in the graph are connected to each other.
Output Format
Output N lines, numbered from small to large, and output the result. The i-th line indicates the number of places that Mr. Suantou needs to go through to reach the place numbered i.

sample input

5 5 2 
1 2 
2 3 
2 4 
3 4 
3 5

Sample output

1 
0 
1 
1 
2

AC code

#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
vector<int>biao[1010];
int d[1010];
queue<int>q;

void bfs(int cur)
{
    q.push(cur);
    d[cur]=0;
    while(!q.empty())
    {
        int tmp=q.front();
        q.pop();
        int sz=biao[tmp].size() ;
        for(int i=0;i<sz;i++)
        {   if(d[biao[tmp][i]]==-1){
            q.push(biao[tmp][i]);
            d[biao[tmp][i]]=d[tmp]+1;
        }
        }
    }
    return;
}

int main()
{
    memset(d,-1,sizeof(d));
    int m,n,c;
    cin>>n>>m>>c;
    while(m--)
    {
        int a,b;
        cin>>a>>b;
        biao[a].push_back(b);
        biao[b].push_back(a);
    }
    bfs(c);
    for(int i=1;i<=n;i++)
    {
        cout<<d[i]<<"\n";
    }
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325936811&siteId=291194637