Pagini recente » Cod sursa (job #1748526) | Cod sursa (job #2799278) | Cod sursa (job #718058) | Cod sursa (job #2097478) | Cod sursa (job #2792095)
#include <bits/stdc++.h>
#define NMax 100001
using namespace std;
ifstream fin("dfs.in");
ofstream fout("dfs.out");
bool vizDFS[NMax];
class graf
{
int nrNoduri, nrMuchii;
bool orientat;
vector <int> gr[NMax]; // liste de adiacenta
public:
graf(int n, int m, bool o); // constructor
void Citire_Orientat();
void Citire_Neorientat();
void BFS(int s); // s - nodul de start
void DFS(int s); // s - nodul de start
void Comp_Conexe();
};
graf :: graf(int n, int m, bool o)
{
nrNoduri = n;
nrMuchii = m;
orientat = o;
}
void graf :: Citire_Orientat()
{
for(int i = 1; i <= nrMuchii; ++i)
{
int x, y;
fin >> x >> y;
gr[x].push_back(y);
}
}
void graf :: Citire_Neorientat()
{
for(int i = 1; i <= nrMuchii; ++i)
{
int x, y;
fin >> x >> y;
gr[x].push_back(y);
gr[y].push_back(x);
}
}
void graf :: BFS(int s)
{
bool viz[NMax] = {0};
int distanta[NMax] = {0};
queue <int> q;
viz[s] = 1;
q.push(s);
while(!q.empty())
{
int k = q.front(); // elem din varful cozii
q.pop(); // sterg elem din varful cozii
for(auto i : gr[k])
if(!viz[i])
{
viz[i] = 1;
q.push(i);
distanta[i] = distanta[k] + 1;
}
}
for(int i = 1; i <= nrNoduri; ++i)
if(viz[i])
fout << distanta[i] << " ";
else
fout << -1 << " ";
}
void graf :: DFS(int s)
{
vizDFS[s] = 1;
for(auto i : gr[s])
if(!vizDFS[i])
DFS(i);
}
void graf :: Comp_Conexe()
{
int ct = 0;
for(int i = 1; i <= nrNoduri; ++i)
if(!vizDFS[i])
{
ct++;
DFS(i);
}
fout << ct;
}
int nrNoduri, nrMuchii;
int main()
{
fin >> nrNoduri >> nrMuchii;
graf G(nrNoduri, nrMuchii, 0);
G.Citire_Neorientat();
G.Comp_Conexe();
return 0;
}