Pagini recente » Cod sursa (job #982067) | Cod sursa (job #3138600) | Cod sursa (job #594606) | Cod sursa (job #578222) | Cod sursa (job #209886)
Cod sursa(job #209886)
#include <fstream>
#include <stack>
using namespace std;
typedef struct nod
{
long nr;
nod *urm;
};
nod *gf[100002];
long nrcnx,n,m,zz;
int viz[100002];
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);
}
}
long vizitare(long &zz)
{
for(long i=zz;i<=n;i++)
if(!viz[i]){
zz=i;
return i;
}
return 0;
}
void dfs()
{
zz=1;
int xy=vizitare(zz);
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(zz);
}
}
void scriere()
{
ofstream g("dfs.out");
g<<nrcnx;
g.close();
}
int main()
{
citire();
dfs();
scriere();
return 0;
}