Pagini recente » Cod sursa (job #1969229) | Cod sursa (job #2165642) | Cod sursa (job #2763041) | Cod sursa (job #2819573) | Cod sursa (job #209884)
Cod sursa(job #209884)
#include <fstream>
#include <stack>
using namespace std;
typedef struct nod
{
int nr;
nod *urm;
};
nod *gf[100000];
long nrcnx,n,m;
int viz[100000];
stack<long> s;
void adaug(int x,int y)
{
nod *q=new nod;
q->nr=y;
q->urm=gf[x];
gf[x]=q;
}
void citire()
{
nrcnx=0;
int x,y;
ifstream f("dfs.in");
f>>n>>m;
for(int i=0;i<m;i++)
{
f>>x>>y;
adaug(x,y);
adaug(y,x);
}
}
int vizitare()
{
for(int i=1;i<=n;i++)
if(!viz[i])
return i;
return 0;
}
void dfs()
{
int xy=vizitare();
while(xy){
s.push(xy);
viz[xy]=1;
while(!s.empty())
{
int vf=s.top();
//cout<<vf<<" ";
s.pop();
for(nod *o=gf[vf];o;o=o->urm)
if(!viz[o->nr])
{
viz[o->nr]=1;
s.push(o->nr);
}
}
nrcnx++;
xy=vizitare();
}
}
void scriere()
{
ofstream g("dfs.out");
g<<nrcnx;
g.close();
}
int main()
{
citire();
dfs();
scriere();
return 0;
}