Pagini recente » fmi-no-stress-2012/solutii/costperm | Cod sursa (job #745084) | Cod sursa (job #1256206) | Cod sursa (job #2844053) | Cod sursa (job #3154580)
#include <bits/stdc++.h>
using namespace std;
ifstream f("bfs.in");
ofstream g("bfs.out");
const int nmax = 100001;
int mat[1001][1001];
list<int> G[nmax];
void grafMatrice(bool orientare, int mat[][1001]){
int n, m;
f >> n >> m;
for(int i = 0; i < m; ++i){
int x, y;
f >> x >> y;
mat[x][y] = 1;
if(!orientare) mat[y][x] = 1;
}
for(int i = 1; i <= n; ++i){
for(int j = 1; j <= m; ++j){
cout << mat[i][j] << " ";
}
cout << '\n';
}
}
void bfs(int x, list<int> G[], int n){
int vis[nmax], d[nmax];
for(int i = 1; i <= n; ++i){
d[i] = -1;
}
queue<int> q;
q.push(x);
d[x] = 0;
vis[x] = 1;
while(!q.empty()){
x = q.front();
q.pop();
for(auto next: G[x]){
if(!vis[next]){
q.push(next);
vis[next] = 1;
d[next] = d[x] + 1;
}
}
}
for(int i = 1; i <= n; ++i){
g << d[i] << " ";
}
}
void grafListe(list<int> G[]){
int n, m, nod;
f >> n >> m >> nod;
for(int i = 0; i < m; ++i){
int x, y;
f >> x >> y;
G[x].push_back(y);
}
bfs(nod, G, n);
}
void toMatr(list<int> G[],int n, bool orientare){
int m[1001][1001];
for(int i = 1; i <= n; ++i){
for(auto nod : G[i]){
for(auto vecin: G[nod]){
m[nod][vecin] = 1;
if(!orientare) m[vecin][nod] = 1;
}
}
}
}
void toList(int mat[1001][1001],int n, int m, bool orientare){
list<int>G[100001];
for(int i = 1; i <= n; ++i){
for(int j = 1; j <= m; ++j){
if(mat[i][j]){
G[i].push_back(j);
if(!orientare) G[j].push_back(i);
}
}
}
}
void dfs(int x){
int vis[nmax];
cout << x << " ";
vis[x] = 1;
for(auto next: G[x]){
if(!vis[next]){
dfs(next);
}
}
}
int main()
{
//grafMatrice(orientare, mat);
grafListe(G);
return 0;
}