Cod sursa(job #710599)

Utilizator psycho21rAbabab psycho21r Data 10 martie 2012 11:27:28
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.98 kb
#include <fstream>
#include <vector>
#include <stack>
using namespace std;
bool visited[100000];
int main()
{
    int N, M;
    ifstream in("dfs.in");
    in >> N >> M;
    vector <int> graph[100000];
    stack<int> st;
    for(int i = 0, a, b; i < M; ++i)
    {
        in >> a >> b;
        graph[a-1].push_back(b-1);
        graph[b-1].push_back(a-1);
    }
    in.close();
    int con = 0;
    for(int i = 0; i < N; ++i)
    {
        if(!visited[i])
        {
            st.push(i);
            while(!st.empty())
            {
                int now = st.top();
                st.pop();
                visited[now] = true;
                for(int i = 0; i < graph[now].size(); ++i)
                {
                    if(!visited[graph[now][i]])
                        st.push(graph[now][i]);
                }
            }
            ++con;
        }
    }
    ofstream out("dfs.out");
    out << con << "\n";
    out.close();
    return 0;
}