Pagini recente » Cod sursa (job #2364816) | Cod sursa (job #1553097) | Cod sursa (job #1971972) | Cod sursa (job #1590270) | Cod sursa (job #900949)
Cod sursa(job #900949)
#include <stack>
#include <vector>
#include <fstream>
#include <algorithm>
using namespace std;
const int Max = 32001;
int noNodes, noEdges, nextNode, countConexity, Mark[Max];
bool Adj[Max][Max];
stack<int> st;
vector<int> v;
void readData (fstream &in){
int _nodeA, _nodeB;
in >> noNodes >> noEdges;
for (int i = 1; i <= noEdges; ++i){
in >> _nodeA >> _nodeB;
Adj[_nodeA][_nodeB] = Adj[_nodeB][_nodeA] = true;
}
in.close();
}
void depthFirstSearch (){
st.push(nextNode);
while (!st.empty()){
int t = st.top();
for (int i = noNodes; i >= 0; --i){
if (Adj[t][i] && find(v.begin(), v.end(), i) == v.end()){
st.push(i);
}
}
if (find(v.begin(), v.end(), t) == v.end()){
v.push_back(t);
Mark[t] = countConexity;
}
else{
st.pop();
}
}
}
void gotoNextNode(){
for (int i = 1; i <= noNodes; ++i){
if (!Mark[i]){
nextNode = i;
return;
}
else if (i == noNodes && Mark[i]){
nextNode = 0;
return;
}
}
}
void findConexityComponents (fstream &out){
nextNode = 1;
countConexity = 1;
while (nextNode){
while (!st.empty()){
st.pop();
}
v.clear();
depthFirstSearch();
countConexity++;
gotoNextNode();
}
out << --countConexity;
}
int main (int argc, char *argv[]){
fstream in("dfs.in", ios::in);
fstream out("dfs.out", ios::out);
readData(in);
findConexityComponents(out);
return 0;
}