-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMulti-source BFS
More file actions
51 lines (50 loc) · 1.05 KB
/
Multi-source BFS
File metadata and controls
51 lines (50 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include<bits/stdc++.h>
using namespace std;
vector<int>grap[1000000];
bool vis[10000];
int dist[1000000],i,u,v,src;
void multisource(vector<int>sources)
{
queue<int>Q;
for(i=0; i<sources.size(); i++)
{
vis[sources[i]]=1;
dist[sources[i]]=0;
Q.push(sources[i]);
}
while(!Q.empty())
{
int first=Q.front();
Q.pop();
for(i=0; i<grap[first].size(); i++)
{
if(vis[grap[first][i]]==0)
{
vis[grap[first][i]] =1;
dist[grap[first][i]]=dist[first]+1;
Q.push(grap[first][i]);
}
}
}
}
int main()
{
int i,j,node,edge,source;
cin>>node>>edge;
for(i=1; i<=edge; i++)
{
cin>>u>>v;
grap[u].push_back(v);
grap[v].push_back(u);
}
cin>>source;
vector<int>sources;
for(i=1; i<=source; i++)
{
cin>>src;
sources.push_back(src);
}
multisource(sources);
for(i=1; i<=node; i++)
cout<<"distance of "<<i<<" = "<<dist[i]<<endl;
}