Pagini recente » Cod sursa (job #34517) | Borderou de evaluare (job #37554) | Cod sursa (job #299764) | Cod sursa (job #2415551) | Cod sursa (job #2783717)
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>
#include <cstring>
#include <algorithm>
using namespace std;
ifstream in("bfs.in");
ofstream out("bfs.out");
vector<int> adj[100005];
queue<int> q;
bool vis[100005];
int dist[100005];
class Graph{
public:
int noduri, muchii;
Graph(int _noduri, int _muchii): noduri(_noduri), muchii(_muchii){
/*for(int i = 0; i < _noduri + 1; ++i)
{ vector <int> temp;
adj.push_back(temp);
}
*/
for(int i = 0; i < 1005; ++i)
dist[i] = -1;
}
/*int get_size(){
return adj.size();
}*/
void build(){
for(int i = 0; i < muchii; ++i)
{
int x, y;
in >> x >> y;
adj[x].push_back(y);
}
}
void print(){
for(int i = 1; i < noduri + 1; ++i)
{ cout << i << ": ";
for(unsigned j = 0; j < adj[i].size(); ++j)
cout << adj[i][j] << " ";
cout << "\n";
}
}
void dfs(int nod){
//cout << nod << " ";
vis[nod] = true;
for(unsigned i = 0; i < adj[nod].size(); ++i)
if(!(vis[adj[nod][i]]))
dfs(adj[nod][i]);
}
long long getCconexe(){
long long cnt = 0;
for(int i = 1; i <= noduri; ++i)
if(!(vis[i]))
{
++cnt;
dfs(i);
}
return cnt;
}
void bfs(int source){
vis[source] = true;
q.push(source);
dist[source] = 0;
while(!q.empty())
{
cout << q.front() << " ";
int crt = q.front();
vis[crt] = 1;
q.pop();
for(int i = 0; i < adj[crt].size(); ++i)
{
if(!vis[adj[crt][i]])
{
dist[adj[crt][i]] = 1 + dist[crt];
q.push(adj[crt][i]);
//vis[adj[crt][i]] = true;
}
}
}
}
void sol(){
for(int i = 0; i < noduri; ++i)
cout << dist[i] << " ";
}
};
int main()
{
int N, M, S;
in >> N >> M;
Graph g(N, M);
in >> S;
g.build();
g.print();
g.bfs(S);
for(int i = 1; i <= g.noduri; ++i)
out << g.dist[i] << " ";
return 0;
}