Cod sursa(job #1429680)

Utilizator sing_exFMIGhita Tudor sing_ex Data 6 mai 2015 22:32:35
Problema Parcurgere DFS - componente conexe Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.03 kb
#include <iostream>
#include <stack>
#include <fstream>
#include <time.h>

using namespace std;

int a[5000][5000],n,m,*v;

void dfs (int x) {
    stack<int> s;
    s.push(x);
    v[x] = 1;
    int ok;
    while (!s.empty()) {
        ok = 1;
        int e = s.top();
        int i;
        for (i=1;i<=n;i++) {
            if (a[e][i] && !v[i]) {
                v[i] = 1;
                s.push(i);
                ok = 0;
                break;
            }
        }
        if (ok) s.pop();
    }
}

int checkv() {
    int i;
    for (i=1;i<=n;i++) if (!v[i]) return 0;
    return 1;
}
int main()
{
    ifstream f("dfs.in");
    f>>n>>m;
    v = new int[n+1];
    int i,x,y,c = 0;
    for (i=1;i<=n;i++) v[i] = 0;
    while (f>>x>>y) {
        a[x][y] = 1;
        a[y][x] = 1;
    }
    f.close();
    for (i=1;i<=n;i++) if (!v[i]) {
        dfs(i);
        c++;
    }
    //cout<<c<<" "<<(float)clock()/CLOCKS_PER_SEC;
    ofstream g("dfs.out");
    g<<c;
    g.close();
    return 0;
}