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