Pagini recente » Cod sursa (job #3183819) | Cod sursa (job #1409004) | Cod sursa (job #114353) | Cod sursa (job #1067172) | Cod sursa (job #2850811)
#include <iostream>
#include <fstream>
#include <vector>
#include <map>
#include <queue>
using namespace std;
ifstream fin("dfs.in");
ofstream fout("dfs.out");
const int MAX_SIZE = 2 * 100005;
vector<int> graph[MAX_SIZE];
int goneThrough[MAX_SIZE];
int totalComponents = 0;
void DFS(int currentPeak) {
queue<int> positions;
int ok = 0;
positions.push(currentPeak);
if (goneThrough[currentPeak] == 0) {
goneThrough[currentPeak] = 1;
ok = 1;
}
while (!positions.empty()) {
int currentPeak = positions.front();
for (int i = 0; i < graph[currentPeak].size(); ++i) {
int nextPoint = graph[currentPeak][i];
if (goneThrough[nextPoint] == 0) {
positions.push(nextPoint);
goneThrough[nextPoint] = 1;
}
}
positions.pop();
}
if (ok) {
++totalComponents;
}
}
int main() {
int peaks, arches;
fin >> peaks >> arches;
for (int i = 1; i <= arches; ++i) {
int start, end;
fin >> start >> end;
graph[start].push_back(end);
graph[end].push_back(start);
}
/*
for (int i = 1; i <= peaks; ++i) {
cout << i << ": ";
for (int j = 0; j < graph[i].size(); ++j) {
cout << graph[i][j] << " ";
}
cout << "\n";
}
*/
for (int j = 1; j <= peaks; ++j) {
DFS(j);
}
fout << totalComponents;
return 0;
}
/*
Ideea: avem un array pentru a marca daca am trecut deja prin punctul respectiv.
Ne folosim de o coada pentru a adauga elementele noi.
Cand coada e goala si daca am parcurs vreun element, adunam cu 1 componentele conexe
Teste:
6 4
1 2
3 2
3 4
5 6 -> 2
6 0 -> 6
1 0 -> 1
6 1
1 2 -> 5
6 5
1 2
2 3
3 4
4 5
5 6 -> 1
6 5
1 2
2 1
3 4
4 3
3 5 -> 3
5 8
1 2
2 1
2 3
3 2
3 4
4 3
1 4
4 1 -> 2
5 9
1 2
2 1
2 3
3 2
3 4
4 3
1 4
4 1
4 5 -> 1
3 2
1 2
3 2 -> 1
*/