Cod sursa(job #1429908)

Utilizator sing_exFMIGhita Tudor sing_ex Data 7 mai 2015 15:43:27
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.66 kb
#include <iostream>
#include <stack>
#include <fstream>
#include <time.h>

using namespace std;

int n,m,*v;

class nod {
    int info;
    nod *next;
public:
    nod() {
        next = NULL;
    }
    nod (int x) {
        info = x;
        next = NULL;
    }
    nod* getNext() {
        return next;
    }
    void setNext(nod *p) {
        next = p;
    }
    int getInfo() {
        return info;
    }
};

nod **nodes;

void dfs (int x) {
    stack<int> s;
    s.push(x);
    v[x] = 1;
    int ok;
    while (!s.empty()) {
        ok = 1;
        int e = s.top();
        nod *p = nodes[e];
        while (p) {
            int a = p->getInfo();
            if (!v[a]) {
                v[a] = 1;
                s.push(a);
                ok = 0;
                break;
            }
            p = p->getNext();
        }
        if (ok) s.pop();
    }
}

void addnod(nod* &p,int x) {
    if (!p) p = new nod(x);
    else {
        nod *q = p;
        while (q->getNext()) q = q->getNext();
        q->setNext(new nod(x));
    }
}

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;
    nodes = new nod*[n+1];
    for (i=1;i<=n;i++) {
        v[i] = 0;
        nodes[i] = NULL;
    }
    while (f>>x>>y) {
        addnod(nodes[x],y);
        addnod(nodes[y],x);
    }
    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;
}