Pagini recente » Cod sursa (job #1876188) | Cod sursa (job #3269882) | Cod sursa (job #195555) | Cod sursa (job #1734294) | Cod sursa (job #2379792)
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
using namespace std;
ifstream fin("dfs.in");
ofstream fout("dfs.out");
const int nmax=100005;
unsigned int n,m;
bool viz[nmax];
vector < int> nod[nmax];
int nr=0;
void DFS_iterativ(int x)
{
//int st[nmax]= {0};
stack<int>st;
st.push(x);
//viz[x]=1;
while(!st.empty())
{
int el_din_varf=st.top();///iau elementul din varful stivei
st.pop();///il si scot dupa ce l folosesc
for(int i=0; i<nod[el_din_varf].size(); i++)
{
///ii parcurg vecinii si ii marchez corespunzator
int next=nod[el_din_varf][i];
if(!viz[next])
{
viz[next]=1;
st.push(next);
}
}
}
}
void DFS(int x)
{
viz[x]=1;
for(int i=0; i<nod[x].size(); i++)
{
int next=nod[x][i];
if(!viz[next])
DFS(next);
}
}
int main()
{
fin>>n>>m;
while(m--)
{
int x1=0,x2=0;
fin>>x1>>x2;
nod[x1].push_back(x2);
nod[x2].push_back(x1);
}
/* for(int i=1; i<=n; i++)
{
cout<<"nodul "<<i<<" are "<<nod[i].size()<<" vecini\n";
for(int j=0; j<nod[i].size(); j++)
cout<<nod[i][j]<<" ";
cout<<endl;
}*/
for(int i=1; i<=n; i++)
{
if(!viz[i])
{
nr++;
DFS_iterativ(i);
}
}
fout<<nr;
}