Pagini recente » Cod sursa (job #914019) | Cod sursa (job #1435068) | Cod sursa (job #1528270) | Cod sursa (job #1678444) | Cod sursa (job #2657540)
#include <iostream>
#include <fstream>
#include <stack>
using namespace std;
ifstream fin("dfs.in");
ofstream fout("dfs.out");
struct nod
{
int val;
nod *next;
};
nod *l[100001];
int n,m;
int fr[100001];
void adauga(int i, int j)
{
if(l[i]==NULL)
{
l[i]=new nod;
l[i]->val=j;
l[i]->next=NULL;
}
else
{
nod *p=new nod;
p->val=j;
p->next=l[i];
l[i]=p;
}
}
void citire()
{
fin>>n>>m;
for(int i=1;i<=m;i++)
{
int x,y;
fin>>x>>y;
adauga(x,y);
adauga(y,x);
}
}
void dfs(int s, int &cnt)
{
stack<int> st;
st.push(s);
while(!st.empty())
{
int top=st.top();
st.pop();
bool ok=true;
for(nod *p=l[top];p!=NULL;p=p->next)
{
if(fr[p->val]==0)
{
ok=false;
fr[p->val]=fr[top]+1;
st.push(p->val);
}
}
if(ok==true) cnt++;
}
}
void rezolva(int &cnt)
{
cnt=0;
for(int i=1;i<=n;i++)
{
if(fr[i]==0 and l[i]!=NULL)
{
dfs(i,cnt);
}
}
}
int main()
{
int cnt=0;
citire();
rezolva(cnt);
fout<<cnt;
return 0;
}