Pagini recente » Cod sursa (job #2456697) | tema | Cod sursa (job #1789553) | Cod sursa (job #2705602) | Cod sursa (job #1691100)
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
#include <fstream>
using namespace std;
ifstream f("dfs.in");
ofstream g("dfs.out");
int n,m,i,j,nr;
vector <vector <int> > graph(100000);
vector <bool> visited (100000,false);
void dfs(int vertex)
{ if(vertex<0||vertex>n-1)
return;
stack <int> s;
int element,i;
bool found;
s.push(vertex);
visited[vertex]=true;
//cout<<vertex+1<<" ";
while(!s.empty())
{ element=s.top();
found=false;
for(i=0;i<graph[element].size()&&(!found);i++)
if(!visited[graph[element][i]])
found=true;
if(found)
{ i--;
s.push(graph[element][i]);
//cout<<graph[element][i]+1<<" ";
visited[graph[element][i]]=true;
}
else s.pop();
}
}
int main()
{ int x,y,s;
f>>n>>m>>s;
for(i=0;i<m;i++)
{ f>>x>>y;
x--; y--;
graph[x].push_back(y);
//graph[y].push_back(x);
}
for(i=0;i<n;i++)
if(!visited[i])
{ dfs(i);
nr++;
}
g<<nr;
return 0;
}