Pagini recente » Cod sursa (job #1922676) | Cod sursa (job #1281068) | Cod sursa (job #2366170) | Cod sursa (job #2325538) | Cod sursa (job #1710833)
#include <iostream>
#include <vector>
#include <stack>
#include <fstream>
using namespace std;
vector < vector<int> > graph;
vector <bool> visited;
int n,m,c;
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;
while(!s.empty()) {
element=s.top();
found=false;
for(i=0;i<graph[element].size() && !found;i++)
if(!visited[graph[element][i]]) found=true,c++;
if(found) {
i--;
s.push(graph[element][i]);
visited[graph[element][i]]=true;
}
else s.pop();
}
}
int main()
{
ifstream f("dfs.in");
ofstream g("dfs.out");
int x,y;
f>>n>>m;
graph.resize(n);
visited.resize(n,false);
for(int i=0; i<m; i++) {
f>>x>>y;
x--;
y--;
graph[x].push_back(y);
graph[y].push_back(x);
}
c=0;
for(int i=0; i<visited.size() && i<n;i++)
if(!visited[i]) dfs(i);
g<<c;
return 0;
}