Pagini recente » Cod sursa (job #2070963) | Cod sursa (job #1659600) | Cod sursa (job #28287) | Cod sursa (job #3139403) | Cod sursa (job #534125)
Cod sursa(job #534125)
// http://infoarena.ro/problema/dfs
#include <fstream>
#include <list>
using namespace std;
#define maxSize 100001
int nodes,edges,conexComponents;
list<int> graph[maxSize];
bool visited[maxSize];
void read();
void findConexComponents();
void depthFirst(int startNode);
void write();
int main() {
read();
findConexComponents();
write();
return (0);
}
void read() {
ifstream in("dfs.in");
int from,to;
in >> nodes >> edges;
// graph.resize(nodes+1);
// visited.resize(nodes+1);
for(int i=1;i<=edges;++i) {
in >> from >> to;
graph[from].push_back(to);
graph[to].push_back(from);
}
in.close();
}
void findConexComponents() {
for(int i=1;i<=nodes;++i)
if(!visited[i]) {
depthFirst(i);
conexComponents++;
}
}
void depthFirst(int toVisit) {
visited[toVisit] = true;
list<int>::iterator end = graph[toVisit].end();
for(list<int>::iterator it=graph[toVisit].begin();it!=end;++it)
if(!visited[*it])
depthFirst(*it);
}
void write() {
ofstream out("dfs.out");
out << conexComponents << "\n";
out.close();
}