Cod sursa(job #345095)

Utilizator AstronothingIulia Comsa Astronothing Data 1 septembrie 2009 17:48:01
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include <fstream>
#include <stack>
#include <vector>
#include <queue>

using namespace std;

vector<int> list[100001];
int viz[100001];
int nr;

void dfs(int start)
{
    stack<int> s;
    s.push(start);
    viz[start] = 1;
    while(!s.empty())
    {
        int crt = s.top();
        s.pop();
        for(int i=0;i<list[crt].size();++i)
            if(!viz[list[crt][i]])
            {
                viz[list[crt][i]] = 1;
                s.push(list[crt][i]);
            }
    }
}

void bfs(int start)
{
    queue<int> q;
    q.push(start);
    viz[start] = 1;
    while(!q.empty())
    {
        int crt = q.front();
        q.pop();
        for(int i=0;i<list[crt].size();++i) if(!viz[list[crt][i]])
        {
            viz[list[crt][i]] = 1;
            q.push(list[crt][i]);
        }

    }
}

int main()
{
    ifstream f("dfs.in");
    ofstream f2("dfs.out");
    int n,m;
    f>>n>>m;
    int x,y;
    while(f>>x>>y)
    {
        list[x-1].push_back(y-1);
        list[y-1].push_back(x-1);
    }
    for(int i=0; i<n; ++i)
    {
        if(!viz[i])
        {
            bfs(i);
            ++nr;
        }
    }
    f2<<nr;
    return 0;
}