Pagini recente » Cod sursa (job #2298376) | Cod sursa (job #1961568) | Cod sursa (job #2356498) | Cod sursa (job #1572208) | Cod sursa (job #1539381)
// infoarenaDFSnonRec.cpp : Defines the entry point for the console application.
//
//#include "stdafx.h"
#include <vector>
#include <fstream>
#include <stack>
#define MaxN 100005
using namespace std;
ifstream fin("dfs.in");
ofstream fout("dfs.out");
int N, M,x, y;
vector<int> G[MaxN];
bool visited[MaxN];
short neighIndexes[MaxN];
stack<int> mystack;
void dfs(int src) {
visited[src] = true;
mystack.push(src);
while (!mystack.empty()) {
int node = mystack.top();
while (neighIndexes[node] < G[node].size() && visited[neighIndexes[node]])
++neighIndexes[node];
if (neighIndexes[node] != G[node].size()) {
int next = G[node][neighIndexes[node]];
visited[next] = true;
mystack.push(next);
}
else {
mystack.pop();
}
}
}
int main()
{
fin >> N >> M;
for (int i = 1; i <= M; ++i) {
fin >> x >> y;
G[x].push_back(y);
G[y].push_back(x);
}
int count = 0;
for (int i = 1; i <= N; ++i) {
if (!visited[i]) {
dfs(i);
++count;
}
}
fout << count << '\n';
return 0;
}